aboutsummaryrefslogtreecommitdiffstats
path: root/container-search/src/main/java/com/yahoo/prelude/semantics/rule/LiteralPhraseProduction.java
blob: aafb740de1dd675c88a7bac20323f8bfd6c3fe33 (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
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.semantics.rule;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import com.yahoo.prelude.query.PhraseItem;
import com.yahoo.prelude.query.WordItem;
import com.yahoo.prelude.semantics.engine.Match;
import com.yahoo.prelude.semantics.engine.RuleEvaluation;
import com.yahoo.protect.Validator;

/**
 * A literal phrase produced by a production rule
 *
 * @author bratseth
 */
public class LiteralPhraseProduction extends TermProduction {

    private final List<String> terms = new ArrayList<>();

    /** Creates a new produced literal phrase */
    public LiteralPhraseProduction() {
        super();
    }

    /**
     * Creates a new produced literal phrase
     *
     * @param label the label of the produced term
     */
    public LiteralPhraseProduction(String label) {
        super(label);
    }

    /** Adds a term to this phrase */
    public void addTerm(String term) {
        Validator.ensureNotNull("A term in a produced phrase",term);
        terms.add(term);
    }

    /** Returns a read only view of the terms produced by this, never null */
    public List<String> getTerms() { return Collections.unmodifiableList(terms); }

    public void produce(RuleEvaluation e, int offset) {
        PhraseItem newPhrase = new PhraseItem();
        newPhrase.setIndexName(getLabel());
        for (String term : terms)
            newPhrase.addItem(new WordItem(term));

        Match matched = e.getNonreferencedMatch(0);
        insertMatch(e, matched, List.of(newPhrase), offset);
    }

    public String toInnerTermString() {
        return getLabelString() + "\"" + getSpaceSeparated(terms) + "\"";
    }

    private String getSpaceSeparated(List<String> terms) {
        StringBuilder builder = new StringBuilder();
        for (Iterator<String> i = terms.iterator(); i.hasNext(); ) {
            builder.append(i.next());
            if (i.hasNext())
                builder.append(" ");
        }
        return builder.toString();
    }

}