2006-09-10 Francisco Javier F. Serrador <serrador@openshine.com>
[beagle.git] / beagled / Lucene.Net / Search / PrefixQuery.cs
blob1bcba624274ba3ac27522249e05ed447f7bc0c07
1 /*
2 * Copyright 2004 The Apache Software Foundation
3 *
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
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
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.
16 using System;
17 using IndexReader = Lucene.Net.Index.IndexReader;
18 using Term = Lucene.Net.Index.Term;
19 using TermEnum = Lucene.Net.Index.TermEnum;
20 namespace Lucene.Net.Search
23 /// <summary>A Query that matches documents containing terms with a specified prefix. </summary>
24 [Serializable]
25 public class PrefixQuery:Query
27 private Term prefix;
29 /// <summary>Constructs a query for terms starting with <code>prefix</code>. </summary>
30 public PrefixQuery(Term prefix)
32 this.prefix = prefix;
35 /// <summary>Returns the prefix of this query. </summary>
36 public virtual Term GetPrefix()
38 return prefix;
41 public override Query Rewrite(IndexReader reader)
43 BooleanQuery query = new BooleanQuery(true);
44 TermEnum enumerator = reader.Terms(prefix);
45 try
47 System.String prefixText = prefix.Text();
48 System.String prefixField = prefix.Field();
49 do
51 Term term = enumerator.Term();
52 if (term != null && term.Text().StartsWith(prefixText) && (System.Object) term.Field() == (System.Object) prefixField)
54 TermQuery tq = new TermQuery(term); // found a match
55 tq.SetBoost(GetBoost()); // set the boost
56 query.Add(tq, BooleanClause.Occur.SHOULD); // add to query
57 //System.out.println("added " + term);
59 else
61 break;
64 while (enumerator.Next());
66 finally
68 enumerator.Close();
70 return query;
73 public override Query Combine(Query[] queries)
75 return Query.MergeBooleanQueries(queries);
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());
85 buffer.Append(":");
87 buffer.Append(prefix.Text());
88 buffer.Append('*');
89 if (GetBoost() != 1.0f)
91 System.Globalization.NumberFormatInfo nfi = new System.Globalization.CultureInfo("en-US", false).NumberFormat;
92 nfi.NumberDecimalDigits = 1;
94 buffer.Append("^");
95 buffer.Append(GetBoost().ToString("N", nfi));
97 return buffer.ToString();
99 override public System.Object Clone()
101 return null;