Fulfilling Lucene Search Query

I search for documents containing text entered by the user

It works fine if there are no special characters in searchText.

The following describes how I create my QueryParser.

//analyzer is an StandardAnalyzer() QueryParser parser = new QueryParser("Text", analyzer); parser.SetAllowLeadingWildcard(true); return parser.Parse(string.Format("*{0}*", searchText)); 

I get the following error if the search text contains any special character:

suppose the search text is "bed ["

 Cannot parse '*bed [*': Encountered "<EOF>" at line 1, column 7. 

How can I make my query analyzer not crash if there are special characters in the search text, and also I do not want to ignore special characters.

+4
source share
2 answers

Try using:

 QueryParser parser = new QueryParser("Text", analyzer); parser.SetAllowLeadingWildcard(true); var escapedSearchText = QueryParser.Escape(searchText); return parser.Parse(string.Format("*{0}*", escapedSearchText)); 

i.e. Avoid search text before creating a query.

Hope this helps,

+6
source

Lucene supports escaping special characters that are part of the query syntax. Special characters in the current list

    • && ||! () {} [] ^ "~ *?: \

To avoid these characters, use the \ character before the character. For example, to search for (1 + 1): 2, use the query:

(1 + 1) \: 2

0
source

All Articles