aboutsummaryrefslogtreecommitdiffstats
path: root/config-model/src/main/java/com/yahoo/vespa/model/search/DocumentSelectionConverter.java
blob: 89d2bdaf54f7d1c0cc829134dd5934665a3241c6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.search;

import com.yahoo.document.select.*;
import com.yahoo.document.select.convert.SelectionExpressionConverter;
import com.yahoo.document.select.parser.ParseException;
import java.util.Map;

/**
 * @author Ulf Lilleengen
 */
// TODO: This should be renamed to reflect it is only a validator of expressions
//       (in DocumentSelector and SelectionExpressionConverter)
public class DocumentSelectionConverter {

    private final DocumentSelector selector;
    private final Map<String, String> queryExpressionMap;

    public DocumentSelectionConverter(String selection) throws ParseException, UnsupportedOperationException, IllegalArgumentException {
        this.selector = new DocumentSelector(selection);
        NowCheckVisitor nowChecker = new NowCheckVisitor();
        selector.visit(nowChecker);
        if (nowChecker.requiresConversion()) {
            SelectionExpressionConverter converter = new SelectionExpressionConverter();
            selector.visit(converter);
            this.queryExpressionMap = converter.getQueryMap();
        } else {
            this.queryExpressionMap = null;
        }
    }

    /**
     * Transforms the selection into a search query.
     *
     * @return a search query representing the selection
     */
    public String getQuery(String documentType) {
        if (queryExpressionMap == null)
            return null;
        if (!queryExpressionMap.containsKey(documentType))
            return null;
        return queryExpressionMap.get(documentType);
    }

    /**
     * Transforms the selection into an inverted search query.
     *
     * @return a search query representing the selection
     */
    public String getInvertedQuery(String documentType) {
        String query = getQuery(documentType);
        if (query == null)
            return null;
        return query.replaceAll(">", "<");
    }

}