2 * Copyright 2004 The Apache Software Foundation
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 using IndexReader
= Lucene
.Net
.Index
.IndexReader
;
19 using Term
= Lucene
.Net
.Index
.Term
;
20 using TermEnum
= Lucene
.Net
.Index
.TermEnum
;
21 using ToStringUtils
= Lucene
.Net
.Util
.ToStringUtils
;
23 namespace Lucene
.Net
.Search
26 /// <summary>A Query that matches documents containing terms with a specified prefix. A PrefixQuery
27 /// is built by QueryParser for input like <code>app*</code>.
30 public class PrefixQuery
: Query
34 /// <summary>Constructs a query for terms starting with <code>prefix</code>. </summary>
35 public PrefixQuery(Term prefix
)
40 /// <summary>Returns the prefix of this query. </summary>
41 public virtual Term
GetPrefix()
46 public override Query
Rewrite(IndexReader reader
)
48 BooleanQuery query
= new BooleanQuery(true);
49 TermEnum enumerator
= reader
.Terms(prefix
);
52 System
.String prefixText
= prefix
.Text();
53 System
.String prefixField
= prefix
.Field();
56 Term term
= enumerator
.Term();
57 if (term
!= null && term
.Text().StartsWith(prefixText
) && term
.Field() == prefixField
)
59 TermQuery tq
= new TermQuery(term
); // found a match
60 tq
.SetBoost(GetBoost()); // set the boost
61 query
.Add(tq
, BooleanClause
.Occur
.SHOULD
); // add to query
62 //System.out.println("added " + term);
69 while (enumerator
.Next());
78 /// <summary>Prints a user-readable version of this query. </summary>
79 public override System
.String
ToString(System
.String field
)
81 System
.Text
.StringBuilder buffer
= new System
.Text
.StringBuilder();
82 if (!prefix
.Field().Equals(field
))
84 buffer
.Append(prefix
.Field());
87 buffer
.Append(prefix
.Text());
89 buffer
.Append(ToStringUtils
.Boost(GetBoost()));
90 return buffer
.ToString();
93 /// <summary>Returns true iff <code>o</code> is equal to this. </summary>
94 public override bool Equals(System
.Object o
)
96 if (!(o
is PrefixQuery
))
98 PrefixQuery other
= (PrefixQuery
) o
;
99 return (this.GetBoost() == other
.GetBoost()) && this.prefix
.Equals(other
.prefix
);
102 /// <summary>Returns a hash code value for this object.</summary>
103 public override int GetHashCode()
105 return BitConverter
.ToInt32(BitConverter
.GetBytes(GetBoost()), 0) ^ prefix
.GetHashCode();