Foren

Phrase query for the index field

Montej Shah, geändert vor 6 Jahren.

Phrase query for the index field

Junior Member Beiträge: 48 Beitrittsdatum: 18.02.15 Neueste Beiträge
Hi All,
We have indexed custom entity field named "Description". Now we want to search data based on this field with Lucene.
For ex. find the entity which contains the phrase "the tenth longest storm duration of any Atlantic" in its description.

We are using Lucene API(Verison 3.5) to fire query on the indexed data. We have checked the Liferay use query like below.
description:'tenth longest storm duration ? any Atlantic'

In which stop words are replaced by '?'(Question Mark), We have used the same query with Lucene API but it doesn't work.

Can any one help how to achieve this? We only require the query string, not all code implementation.
Montej Shah, geändert vor 6 Jahren.

RE: Phrase query for the index field

Junior Member Beiträge: 48 Beitrittsdatum: 18.02.15 Neueste Beiträge
With the blessing of the god finally got the solution.
The below shows whole code, based on the plain Lucene API.


public static TopDocs getQueryHitsUsingLuceneAPI(long companyId,
IndexSearcher indexSearcher, int maxHits) throws IOException, ParseException {

// Use Stop Analyzer because of Liferay 6.2 use this analyzer also version 3.5
Analyzer analyzer = new StopAnalyzer(Version.LUCENE_35);
QueryParser queryParser = new QueryParser(Version.LUCENE_35, StringPool.BLANK, analyzer);
// to allow the leasing character as wildcard like * or ? (Not provided while using liferay
// StringQuery)
queryParser.setAllowLeadingWildcard(true);
// Allow to generate case sensitive query
queryParser.setLowercaseExpandedTerms(false);
// Enable positional increments
queryParser.setEnablePositionIncrements(true);
// // parser query using parser
PhraseQuery phraseQuery = new PhraseQuery();
// New Document of the validate the phrase query
phraseQuery.add(new Term("description", "the"));
phraseQuery.add(new Term("description", "tenth"));
phraseQuery.add(new Term("description", "longest"));
phraseQuery.add(new Term("description", "storm"));
phraseQuery.add(new Term("description", "duration"));
phraseQuery.add(new Term("description", "of"));
phraseQuery.add(new Term("description", "any"));
phraseQuery.add(new Term("description", "Atlantic"));
phraseQuery.setSlop(0);
Query query = queryParser.parse(phraseQuery.toString());


log.info("Hits);" + indexSearcher.search(query, maxHits).totalHits);
// query.toString()

log.info("Fire Query:" + query.toString());
return indexSearcher.search(query, maxHits);
}


Above code will replace stop word in phrase query with '?' .
Main things to note down for above code.
  • Here we have use stop analyzer and set enable positional increment for query parser. Which will be used to replace stop word(Here it is "Of") to '?'.
  • "queryParser.setLowercaseExpandedTerms(false)" This will convert capital letter in small letters in your query.