Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Let Lucene include spaces in term for exact match

Tags:

c#

lucene.net

I want my Lucene query to contain something similar to:

companyNam:mercedes trucks

Where it will do an exact match for the string "mercedes trucks" in the companyName field.
The companyName is an untokenized field, but anything with a space returns null results..

new TermQuery(new Term("companyName", "mercedes trucks"));

Always results 0 results if there is a space involved. Otherwise my program is working fine.

like image 970
Boris Callens Avatar asked Mar 09 '09 15:03

Boris Callens


People also ask

How do you use the wildcard in Lucene?

Lucene supports single and multiple character wildcard searches within single terms (not within phrase queries). To perform a single character wildcard search use the "?" symbol. To perform a multiple character wildcard search use the "*" symbol. You can also use the wildcard searches in the middle of a term.

What are Lucene special characters?

You can't search for special characters in Lucene Search. These are + - = && || > < ! ( ) { } [ ] ^ " ~ * ? : \ / @.

What is Lucene query syntax?

What is Lucene Query Syntax? Lucene is a query language that can be used to filter messages in your PhishER inbox. A query written in Lucene can be broken down into three parts: Field The ID or name of a specific container of information in a database.

Can Boolean operators like and/or and so on be used in Lucene query syntax?

You can embed Boolean operators in a query string to improve the precision of a match. The full syntax supports text operators in addition to character operators. Always specify text boolean operators (AND, OR, NOT) in all caps.


2 Answers

Maybe replace:

mercedes trucks 

with

mercedes?trucks

Works for me.

like image 164
derCris Avatar answered Sep 21 '22 06:09

derCris


Use a PhraseQuery like this:

//create the query objects
BooleanQuery query = new BooleanQuery();
PhraseQuery q2 = new PhraseQuery();
//grab the search terms from the query string
string[] str = Sitecore.Context.Request.QueryString[BRAND_TERM].Split(' ');
//build the query
foreach(string word in str)
{
  //brand is the field I'm searching in
  q2.Add(new Term("brand", word.ToLower()));
}

//finally, add it to the BooleanQuery object
query.Add(q2, BooleanClause.Occur.MUST);

//Don't forget to run the query
Hits hits = searcher.Search(query);

Hope this helps!

like image 25
kirk.burleson Avatar answered Sep 22 '22 06:09

kirk.burleson