aboutsummaryrefslogtreecommitdiffstats
path: root/container-search/src/main/java/com/yahoo/prelude/query/WordAlternativesItem.java
blob: ea78b2365c5e332cbc31ed37da6a9a1af49d4bb8 (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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.query;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import com.yahoo.compress.IntegerCompressor;

/**
 * A set of words with differing exactness scores to be used for literal boost ranking.
 *
 * @author Steinar Knutsen
 */
public class WordAlternativesItem extends TermItem {

    private List<Alternative> alternatives;

    public WordAlternativesItem(String indexName, boolean isFromQuery, Substring origin, Collection<Alternative> terms) {
        super(indexName, isFromQuery, origin);
        setAlternatives(terms);
    }

    public void setAlternatives(Collection<Alternative> terms) {
        this.alternatives = uniqueAlternatives(terms);
    }

    private static List<Alternative> uniqueAlternatives(Collection<Alternative> terms) {
        List<Alternative> uniqueTerms = new ArrayList<>(terms.size());
        for (Alternative term : terms) {
            int i = Collections.binarySearch(uniqueTerms, term, (t0, t1) -> t0.word.compareTo(t1.word));
            if (i >= 0) {
                Alternative old = uniqueTerms.get(i);
                if (old.exactness < term.exactness) {
                    uniqueTerms.set(i, term);
                }
            } else {
                uniqueTerms.add(~i, term);
            }
        }
        return List.copyOf(uniqueTerms);
    }

    @Override
    public String stringValue() {
        StringBuilder builder = new StringBuilder();
        builder.append("[ ");
        for (Alternative a : alternatives) {
            builder.append(a.word).append("(").append(a.exactness).append(") ");
        }
        builder.append("]");
        return builder.toString();
    }

    @Override
    public boolean isStemmed() {
        return true;
    }

    @Override
    public int getNumWords() {
        return 1;
    }

    @Override
    public void setValue(String value) {
        throw new UnsupportedOperationException("Semantics for setting to a string would be brittle, use setAlternatives()");
    }

    @Override
    public String getRawWord() {
        if (getOrigin() == null) {
            return stringValue();
        } else {
            return getOrigin().getValue();
        }
    }

    @Override
    public boolean isWords() {
        return true;
    }

    @Override
    public String getIndexedString() {
        return alternatives.stream().map((x) -> x.word).collect(Collectors.joining(" "));
    }

    @Override
    public ItemType getItemType() {
        return ItemType.WORD_ALTERNATIVES; // placeholder
    }

    @Override
    public String getName() {
        return "WORD_ALTERNATIVES";
    }

    /**
     * Return an immutable snapshot of the contained terms. This list will not reflect later changes to the item.
     *
     * @return an immutable list of word alternatives and their respective scores
     */
    public List<Alternative> getAlternatives() {
        return alternatives;
    }

    @Override
    public void encodeThis(ByteBuffer target) {
        super.encodeThis(target);
        IntegerCompressor.putCompressedPositiveNumber(alternatives.size(), target);
        for (Alternative a : alternatives) {
            Item p = new PureWeightedString(a.word, (int) (getWeight() * a.exactness + 0.5));
            p.setFilter(isFilter());
            p.encode(target);
        }
    }

    /**
     * Add a new alternative iff the term string is not already present with an
     * equal or higher exactness score. If the term string is present with a
     * lower exactness score, the new, higher score will take precedence.
     *
     * @param term one of several string interpretations of the input word
     * @param exactness how close the term string matches what the user input
     */
    public void addTerm(String term, double exactness) {
        // do note, Item is Cloneable, and overwriting the reference is what
        // saves us from overriding the method
        if (alternatives.stream().anyMatch((a) -> a.word.equals(term) && a.exactness >= exactness )) return;

        List<Alternative> newTerms = new ArrayList<>(alternatives.size() + 1);
        newTerms.addAll(alternatives);
        newTerms.add(new Alternative(term, exactness));
        setAlternatives(newTerms);
    }

    @Override
    public WordAlternativesItem clone() {
        var clone = (WordAlternativesItem)super.clone();
        clone.alternatives = new ArrayList(this.alternatives);
        return clone;
    }

    @Override
    public boolean equals(Object other) {
        if ( ! super.equals(other)) return false;
        return this.alternatives.equals(((WordAlternativesItem)other).alternatives);
    }

    @Override
    public int hashCode() {
        return Objects.hash(super.hashCode(), alternatives);
    }

    /** A word alternative. This is a value object. */
    public static final class Alternative {

        public final String word;
        public final double exactness;

        public Alternative(String word, double exactness) {
            super();
            this.word = word;
            this.exactness = exactness;
        }

        @Override
        public String toString() {
            return "Alternative [word=" + word + ", exactness=" + exactness + "]";
        }

        @Override
        public boolean equals(Object o) {
            if ( ! (o instanceof Alternative other)) return false;
            if ( ! Objects.equals(this.word, other.word)) return false;
            if (this.exactness != other.exactness) return false;
            return true;
        }

        @Override
        public int hashCode() {
            return Objects.hash(word, exactness);
        }

    }

}