summaryrefslogtreecommitdiff
path: root/core/src/main/java/org/elasticsearch/index/query/FuzzyQueryBuilder.java
blob: 3be82f39704c9cad6b994502022358e502785ce1 (plain)
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
/*
 * Licensed to Elasticsearch under one or more contributor
 * license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright
 * ownership. Elasticsearch licenses this file to you under
 * the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package org.elasticsearch.index.query;

import org.apache.lucene.index.Term;
import org.apache.lucene.search.FuzzyQuery;
import org.apache.lucene.search.MultiTermQuery;
import org.apache.lucene.search.Query;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.lucene.BytesRefs;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.query.support.QueryParsers;

import java.io.IOException;
import java.util.Objects;

/**
 * A Query that does fuzzy matching for a specific value.
 */
public class FuzzyQueryBuilder extends AbstractQueryBuilder<FuzzyQueryBuilder> implements MultiTermQueryBuilder<FuzzyQueryBuilder> {

    public static final String NAME = "fuzzy";

    /** Default maximum edit distance. Defaults to AUTO. */
    public static final Fuzziness DEFAULT_FUZZINESS = Fuzziness.AUTO;

    /** Default number of initial characters which will not be “fuzzified”. Defaults to 0. */
    public static final int DEFAULT_PREFIX_LENGTH = FuzzyQuery.defaultPrefixLength;

    /** Default maximum number of terms that the fuzzy query will expand to. Defaults to 50. */
    public static final int DEFAULT_MAX_EXPANSIONS = FuzzyQuery.defaultMaxExpansions;

    /** Default as to whether transpositions should be treated as a primitive edit operation,
     * instead of classic Levenshtein algorithm. Defaults to false. */
    public static final boolean DEFAULT_TRANSPOSITIONS = false;

    private final String fieldName;

    private final Object value;

    private Fuzziness fuzziness = DEFAULT_FUZZINESS;

    private int prefixLength = DEFAULT_PREFIX_LENGTH;

    private int maxExpansions = DEFAULT_MAX_EXPANSIONS;

    //LUCENE 4 UPGRADE  we need a testcase for this + documentation
    private boolean transpositions = DEFAULT_TRANSPOSITIONS;

    private String rewrite;

    static final FuzzyQueryBuilder PROTOTYPE = new FuzzyQueryBuilder();

    /**
     * Constructs a new fuzzy query.
     *
     * @param fieldName  The name of the field
     * @param value The value of the text
     */
    public FuzzyQueryBuilder(String fieldName, String value) {
        this(fieldName, (Object) value);
    }

    /**
     * Constructs a new fuzzy query.
     *
     * @param fieldName  The name of the field
     * @param value The value of the text
     */
    public FuzzyQueryBuilder(String fieldName, int value) {
        this(fieldName, (Object) value);
    }

    /**
     * Constructs a new fuzzy query.
     *
     * @param fieldName  The name of the field
     * @param value The value of the text
     */
    public FuzzyQueryBuilder(String fieldName, long value) {
        this(fieldName, (Object) value);
    }

    /**
     * Constructs a new fuzzy query.
     *
     * @param fieldName  The name of the field
     * @param value The value of the text
     */
    public FuzzyQueryBuilder(String fieldName, float value) {
        this(fieldName, (Object) value);
    }

    /**
     * Constructs a new fuzzy query.
     *
     * @param fieldName  The name of the field
     * @param value The value of the text
     */
    public FuzzyQueryBuilder(String fieldName, double value) {
        this(fieldName, (Object) value);
    }

    /**
     * Constructs a new fuzzy query.
     *
     * @param fieldName  The name of the field
     * @param value The value of the text
     */
    public FuzzyQueryBuilder(String fieldName, boolean value) {
        this(fieldName, (Object) value);
    }

    /**
     * Constructs a new fuzzy query.
     *
     * @param fieldName  The name of the field
     * @param value The value of the term
     */
    public FuzzyQueryBuilder(String fieldName, Object value) {
        if (Strings.isEmpty(fieldName)) {
            throw new IllegalArgumentException("field name cannot be null or empty.");
        }
        if (value == null) {
            throw new IllegalArgumentException("query value cannot be null");
        }
        this.fieldName = fieldName;
        this.value = convertToBytesRefIfString(value);
    }

    private FuzzyQueryBuilder() {
        // for protoype
        this.fieldName = null;
        this.value = null;
    }

    public String fieldName() {
        return this.fieldName;
    }

    public Object value() {
        return convertToStringIfBytesRef(this.value);
    }

    public FuzzyQueryBuilder fuzziness(Fuzziness fuzziness) {
        this.fuzziness = (fuzziness == null) ? DEFAULT_FUZZINESS : fuzziness;
        return this;
    }

    public Fuzziness fuzziness() {
        return this.fuzziness;
    }

    public FuzzyQueryBuilder prefixLength(int prefixLength) {
        this.prefixLength = prefixLength;
        return this;
    }

    public int prefixLength() {
        return this.prefixLength;
    }

    public FuzzyQueryBuilder maxExpansions(int maxExpansions) {
        this.maxExpansions = maxExpansions;
        return this;
    }

    public int maxExpansions() {
        return this.maxExpansions;
    }

    public FuzzyQueryBuilder transpositions(boolean transpositions) {
      this.transpositions = transpositions;
      return this;
    }

    public boolean transpositions() {
        return this.transpositions;
    }

    public FuzzyQueryBuilder rewrite(String rewrite) {
        this.rewrite = rewrite;
        return this;
    }

    public String rewrite() {
        return this.rewrite;
    }

    @Override
    protected void doXContent(XContentBuilder builder, Params params) throws IOException {
        builder.startObject(NAME);
        builder.startObject(fieldName);
        builder.field(FuzzyQueryParser.VALUE_FIELD.getPreferredName(), convertToStringIfBytesRef(this.value));
        fuzziness.toXContent(builder, params);
        builder.field(FuzzyQueryParser.PREFIX_LENGTH_FIELD.getPreferredName(), prefixLength);
        builder.field(FuzzyQueryParser.MAX_EXPANSIONS_FIELD.getPreferredName(), maxExpansions);
        builder.field(FuzzyQueryParser.TRANSPOSITIONS_FIELD.getPreferredName(), transpositions);
        if (rewrite != null) {
            builder.field(FuzzyQueryParser.REWRITE_FIELD.getPreferredName(), rewrite);
        }
        printBoostAndQueryName(builder);
        builder.endObject();
        builder.endObject();
    }

    @Override
    public String getWriteableName() {
        return NAME;
    }

    @Override
    protected Query doToQuery(QueryShardContext context) throws IOException {
        Query query = null;
        String rewrite = this.rewrite;
        if (rewrite == null && context.isFilter()) {
            rewrite = QueryParsers.CONSTANT_SCORE.getPreferredName();
        }
        MappedFieldType fieldType = context.fieldMapper(fieldName);
        if (fieldType != null) {
            query = fieldType.fuzzyQuery(value, fuzziness, prefixLength, maxExpansions, transpositions);
        }
        if (query == null) {
            int maxEdits = fuzziness.asDistance(BytesRefs.toString(value));
            query = new FuzzyQuery(new Term(fieldName, BytesRefs.toBytesRef(value)), maxEdits, prefixLength, maxExpansions, transpositions);
        }
        if (query instanceof MultiTermQuery) {
            MultiTermQuery.RewriteMethod rewriteMethod = QueryParsers.parseRewriteMethod(context.parseFieldMatcher(), rewrite, null);
            QueryParsers.setRewriteMethod((MultiTermQuery) query, rewriteMethod);
        }
        return query;
    }

    @Override
    protected FuzzyQueryBuilder doReadFrom(StreamInput in) throws IOException {
        FuzzyQueryBuilder fuzzyQueryBuilder = new FuzzyQueryBuilder(in.readString(), in.readGenericValue());
        fuzzyQueryBuilder.fuzziness = Fuzziness.readFuzzinessFrom(in);
        fuzzyQueryBuilder.prefixLength = in.readVInt();
        fuzzyQueryBuilder.maxExpansions = in.readVInt();
        fuzzyQueryBuilder.transpositions = in.readBoolean();
        fuzzyQueryBuilder.rewrite = in.readOptionalString();
        return fuzzyQueryBuilder;
    }

    @Override
    protected void doWriteTo(StreamOutput out) throws IOException {
        out.writeString(this.fieldName);
        out.writeGenericValue(this.value);
        this.fuzziness.writeTo(out);
        out.writeVInt(this.prefixLength);
        out.writeVInt(this.maxExpansions);
        out.writeBoolean(this.transpositions);
        out.writeOptionalString(this.rewrite);
    }

    @Override
    protected int doHashCode() {
        return Objects.hash(fieldName, value, fuzziness, prefixLength, maxExpansions, transpositions, rewrite);
    }

    @Override
    protected boolean doEquals(FuzzyQueryBuilder other) {
        return Objects.equals(fieldName, other.fieldName) &&
                Objects.equals(value, other.value) &&
                Objects.equals(fuzziness, other.fuzziness) &&
                Objects.equals(prefixLength, other.prefixLength) &&
                Objects.equals(maxExpansions, other.maxExpansions) &&
                Objects.equals(transpositions, other.transpositions) &&
                Objects.equals(rewrite, other.rewrite);
    }
}