How to create and search a Lucene.Net index in 4 simple steps using C#, Step 2

Build the Query.

There are numerous ways you can build your query. I counted 17 different Query classes in the Lucene.Net source code. Here is a list of some of the query classes and when to use them.

Query Class Description
TermQuery Searches for a specific term
RangeQuery Searches within a specific range, ex: date range, currency value range
BooleanQuery MUST, MUST_NOT exist in the field
MultiTermQuery Search multiple fields in the same query
NumericRangeQuery Similar to Range, but optimized for numbers
FuzzyQuery Tries to repair incorrectly spelled search parameters
QueryParser Open text, most commonly use query class

To create the query you will need to provide the query with an Analyzer and the field within each document you want to search in.

The analyzer is created like this:
Lucene.Net.Analysis.Analyzer analyzer =
new Lucene.Net.Analysis.Standard.StandardAnalyzer
(Lucene.Net.Util.Version.LUCENE_29);

Then we can create the Query parser:
LuceneQueryParsers.QueryParser parser =
new QueryParser(LuceneUtil.Version.LUCENE_29,
"fieldName", analyzer);

and then finally, we create the query which we will pass to the search method.
Lucene.Net.Search.Query query = parser.Parse(textBoxSearch.Text);

We have now successfully completed step 2 of building an index with Lucene.Net and searching it.




Leave a Comment

Your email address will not be published.