0

How do I get search hits when at least one character searched is present in a field's value, using lucene search?

I got search hits only when I search with a complete word.

Example: Hello world

In above example, if I enter "Hello", then I will get a hit, but not if I enter "Hel"

Here is my code to get hits:

QueryParser parser = null;
Query query = null;
Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT, new HashSet());
BooleanQuery.setMaxClauseCount(32767);
parser = new QueryParser("fieldname", analyzer);
parser.setAllowLeadingWildcard(true);
query = parser.parse("searchString");
TopDocs topResultDocs = searcher.search(query, null, 20);
femtoRgon
  • 32,893
  • 7
  • 60
  • 87

1 Answers1

2

Always append * to the query to get all suffix matches: Hel* will match Hello.

mindas
  • 26,463
  • 15
  • 97
  • 154
  • if Hel present in some string like "abcHelbbc abcdef" also i need to get hit – user3230860 Mar 11 '14 at 14:04
  • If you are trying to replicate SQL `LIKE '%foo%'` behaviour, read this answer: http://stackoverflow.com/questions/3307890/how-to-query-lucene-with-like-operator – mindas Mar 11 '14 at 14:07
  • If you are happy with the answer, you might want to [accept it](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work). This is how this site works. Thank you! – mindas Mar 11 '14 at 14:14
  • for example: In 'Hi Hello world' sentence I need to get hit if i enter 'Hello wo' .what i need to do – user3230860 Mar 12 '14 at 11:36
  • I got solution:TokenStream tokenStream = analyzer.tokenStream(field, new StringReader(searchString)); List tokens = new ArrayList(); TermAttribute termAttribute = (TermAttribute) tokenStream.getAttribute(TermAttribute.class); while (tokenStream.incrementToken()) { String term = termAttribute.term(); tokens.add(term); } BooleanQuery booleanQuery = new BooleanQuery(); for (int i = 0; i < tokens.size(); i++) { booleanQuery.add(new PrefixQuery(new Term(field, tokens.get(i).toString())), Occur.MUST); } TopDocs topResultDocs = searcher.search(booleanQuery, null, 20); – user3230860 Mar 13 '14 at 12:33