Welcome to mirror list, hosted at ThFree Co, Russian Federation.

FuzzyQuery.cs « Search « core « src - github.com/mono/Lucene.Net.Light.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: bdf5af7105c4f57422b86ee79d64555150e0669e (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
/* 
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF 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.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using Lucene.Net.Index;
using Lucene.Net.Support;
using Lucene.Net.Util;
using IndexReader = Lucene.Net.Index.IndexReader;
using Single = Lucene.Net.Support.Single;
using Term = Lucene.Net.Index.Term;
using ToStringUtils = Lucene.Net.Util.ToStringUtils;

namespace Lucene.Net.Search
{
	
	/// <summary>Implements the fuzzy search query. The similarity measurement
	/// is based on the Levenshtein (edit distance) algorithm.
	/// 
	/// Warning: this query is not very scalable with its default prefix
	/// length of 0 - in this case, *every* term will be enumerated and
	/// cause an edit score calculation.
	/// 
	/// </summary>
	[Serializable]
	public class FuzzyQuery : MultiTermQuery
	{
		
		public const float defaultMinSimilarity = 0.5f;
		public const int defaultPrefixLength = 0;
		
		private float minimumSimilarity;
		private int prefixLength;
		private bool termLongEnough = false;

        /// <summary> Returns the pattern term.</summary>
	    public Term Term { get; protected internal set; }

	    /// <summary> Create a new FuzzyQuery that will match terms with a similarity 
		/// of at least <c>minimumSimilarity</c> to <c>term</c>.
		/// If a <c>prefixLength</c> &gt; 0 is specified, a common prefix
		/// of that length is also required.
		/// 
		/// </summary>
		/// <param name="term">the term to search for
		/// </param>
		/// <param name="minimumSimilarity">a value between 0 and 1 to set the required similarity
		/// between the query term and the matching terms. For example, for a
		/// <c>minimumSimilarity</c> of <c>0.5</c> a term of the same length
		/// as the query term is considered similar to the query term if the edit distance
		/// between both terms is less than <c>length(term)*0.5</c>
		/// </param>
		/// <param name="prefixLength">length of common (non-fuzzy) prefix
		/// </param>
		/// <throws>  IllegalArgumentException if minimumSimilarity is &gt;= 1 or &lt; 0 </throws>
		/// <summary> or if prefixLength &lt; 0
		/// </summary>
		public FuzzyQuery(Term term, float minimumSimilarity, int prefixLength)
		{
			this.Term = term;
			
			if (minimumSimilarity >= 1.0f)
				throw new System.ArgumentException("minimumSimilarity >= 1");
			else if (minimumSimilarity < 0.0f)
				throw new System.ArgumentException("minimumSimilarity < 0");
			if (prefixLength < 0)
				throw new System.ArgumentException("prefixLength < 0");
			
			if (term.Text.Length > 1.0f / (1.0f - minimumSimilarity))
			{
				this.termLongEnough = true;
			}
			
			this.minimumSimilarity = minimumSimilarity;
			this.prefixLength = prefixLength;
			internalRewriteMethod = SCORING_BOOLEAN_QUERY_REWRITE;
		}

        /// <summary> Calls <see cref="FuzzyQuery(Index.Term, float)">FuzzyQuery(term, minimumSimilarity, 0)</see>.</summary>
		public FuzzyQuery(Term term, float minimumSimilarity):this(term, minimumSimilarity, defaultPrefixLength)
		{
		}

        /// <summary> Calls <see cref="FuzzyQuery(Index.Term, float)">FuzzyQuery(term, 0.5f, 0)</see>.</summary>
		public FuzzyQuery(Term term):this(term, defaultMinSimilarity, defaultPrefixLength)
		{
		}

	    /// <summary> Returns the minimum similarity that is required for this query to match.</summary>
	    /// <value> float value between 0.0 and 1.0 </value>
	    public virtual float MinSimilarity
	    {
	        get { return minimumSimilarity; }
	    }

	    /// <summary> Returns the non-fuzzy prefix length. This is the number of characters at the start
	    /// of a term that must be identical (not fuzzy) to the query term if the query
	    /// is to match that term. 
	    /// </summary>
	    public virtual int PrefixLength
	    {
	        get { return prefixLength; }
	    }

	    protected internal override FilteredTermEnum GetEnum(IndexReader reader)
		{
			return new FuzzyTermEnum(reader, Term, minimumSimilarity, prefixLength);
		}

	    public override RewriteMethod RewriteMethod
	    {
	        set { throw new System.NotSupportedException("FuzzyQuery cannot change rewrite method"); }
	    }

	    public override Query Rewrite(IndexReader reader)
		{
			if (!termLongEnough)
			{
				// can only match if it's exact
				return new TermQuery(Term);
			}

		    int maxSize = BooleanQuery.MaxClauseCount;

            // TODO: Java uses a PriorityQueue.  Using Linq, we can emulate it, 
            //       however it's considerable slower than the java counterpart.
            //       this should be a temporary thing, fixed before release
            SortedList<ScoreTerm, ScoreTerm> stQueue = new SortedList<ScoreTerm, ScoreTerm>();
			FilteredTermEnum enumerator = GetEnum(reader);
			
			try
			{
                ScoreTerm st = new ScoreTerm();
				do 
				{
					Term t = enumerator.Term;
                    if (t == null) break;
				    float score = enumerator.Difference();
                    //ignore uncompetetive hits
                    if (stQueue.Count >= maxSize && score <= stQueue.Keys.First().score)
                        continue;
                    // add new entry in PQ
				    st.term = t;
				    st.score = score;
				    stQueue.Add(st, st);
                    // possibly drop entries from queue
                    if (stQueue.Count > maxSize)
                    {
                        st = stQueue.Keys.First();
                        stQueue.Remove(st);
                    }
                    else
                    {
                        st = new ScoreTerm();
                    }
				}
				while (enumerator.Next());
			}
			finally
			{
				enumerator.Close();
			}
			
			BooleanQuery query = new BooleanQuery(true);
			foreach(ScoreTerm st in stQueue.Keys)
			{
				TermQuery tq = new TermQuery(st.term); // found a match
				tq.Boost = Boost * st.score; // set the boost
				query.Add(tq, Occur.SHOULD); // add to query
			}
			
			return query;
		}
		
		public override System.String ToString(System.String field)
		{
			System.Text.StringBuilder buffer = new System.Text.StringBuilder();
			if (!Term.Field.Equals(field))
			{
				buffer.Append(Term.Field);
				buffer.Append(":");
			}
			buffer.Append(Term.Text);
			buffer.Append('~');
			buffer.Append(Single.ToString(minimumSimilarity));
			buffer.Append(ToStringUtils.Boost(Boost));
			return buffer.ToString();
		}
		
		protected internal class ScoreTerm : IComparable<ScoreTerm>
		{
			public Term term;
			public float score;

		    public int CompareTo(ScoreTerm other)
		    {
                if (Comparer<float>.Default.Compare(this.score, other.score) == 0)
                {
                    return other.term.CompareTo(this.term);
                }
                else
                {
                    return Comparer<float>.Default.Compare(this.score, other.score);
                }
		    }
		}
		
		public override int GetHashCode()
		{
			int prime = 31;
			int result = base.GetHashCode();
			result = prime * result + BitConverter.ToInt32(BitConverter.GetBytes(minimumSimilarity), 0);
			result = prime * result + prefixLength;
			result = prime * result + ((Term == null)?0:Term.GetHashCode());
			return result;
		}
		
		public  override bool Equals(System.Object obj)
		{
			if (this == obj)
				return true;
			if (!base.Equals(obj))
				return false;
			if (GetType() != obj.GetType())
				return false;
			FuzzyQuery other = (FuzzyQuery) obj;
			if (BitConverter.ToInt32(BitConverter.GetBytes(minimumSimilarity), 0) != BitConverter.ToInt32(BitConverter.GetBytes(other.minimumSimilarity), 0))
				return false;
			if (prefixLength != other.prefixLength)
				return false;
			if (Term == null)
			{
				if (other.Term != null)
					return false;
			}
			else if (!Term.Equals(other.Term))
				return false;
			return true;
		}
	}
}