summaryrefslogtreecommitdiffstats
path: root/container-search/src/main/java/com/yahoo/prelude/query/parser/WebParser.java
blob: d23ca3f4a29ff5b660e56a97560bc83cf894d531 (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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.query.parser;

import com.yahoo.prelude.query.*;
import com.yahoo.search.query.parser.ParserEnvironment;

import java.util.Set;

/**
 * Parser for web search queries. Language:
 *
 * <ul>
 * <li>+item: always include this item as-is when searching (term becomes <i>protected</i>)
 * <li>-item: Exclude item when searching (terms becomes <i>protected</i>)
 * <li>a OR b (capital or): Or search for a or b
 * <li>"a b": Phrase search for a followed by b
 * </ul>
 *
 * @author bratseth
 */
public class WebParser extends AllParser {

    public WebParser(ParserEnvironment environment) {
        super(environment);
    }

    protected @Override Item parseItemsBody() {
        // Algorithm: Collect positive, negative, and'ed and or'ed elements, then combine.
        AndItem and=null;
        OrItem or=null;
        NotItem not=null; // Store negatives here as we go
        Item current;

        // Find all items
        do {
            current=negativeItem();
            if (current!=null) {
                not=addNot(current,not);
                continue;
            }

            current=positiveItem();
            if (current==null)
                current = indexableItem();

            if (current!=null) {
                if (and!=null && (current instanceof WordItem) && "OR".equals(((WordItem)current).getRawWord())) {
                    if (or==null)
                        or=addOr(and,or);
                    and=new AndItem();
                    or.addItem(and);
                }
                else {
                    and=addAnd(current,and);
                }
            }

            if (current == null) // Change
                tokens.skip();
        } while (tokens.hasNext());

        // Combine the items
        Item topLevel=and;

        if (or!=null)
            topLevel=or;

        if (not!=null && topLevel!=null) {
            not.setPositiveItem(topLevel);
            topLevel=not;
        }

        return simplifyUnnecessaryComposites(topLevel);
    }

    protected void setSubmodeFromIndex(String indexName, Set<String> searchDefinitions) {
        // No submodes in this language
    }

}