Saurabh Nemade
Saurabh Nemade

Reputation: 1592

Lucene query modification

I have a requirement where I want to modify string formatted lucene query values. I am taking lucene query as input from user interface and passing it to elastic.

For e.g.

Input : name:"abc" and age:26

Output expected: name: "abcmodified" and userage:26

How do I parse and modify string formatted lucene query in java?

Upvotes: 1

Views: 452

Answers (1)

Almog
Almog

Reputation: 741

Have you tried looking into org.apache.lucene.queryparser.classic.QueryParser? It has functionality to return a Lucene Query Object from an input string. For example:

String rawQuery = "name:abc AND age:26";
QueryParser parser = new QueryParser(Version.LUCENE_45, null, new WhitespaceAnalyzer(Version.LUCENE_45));
BooleanQuery query = (BooleanQuery) praser.parse(rawQuery);
query.clauses().get(0).setQuery(new TermQuery(new Term("name", "abcmodified")));
query.clauses().get(1).setQuery(new TermQuery(new Term("userage", "26")));
System.out.println(query);

Will print +name:abcmodified +userage:26, which is essentially what you want. Obviously you can have smarter processing using a recursive method that traverses the query based on the query type (Boolean, Prefix, Term, Fuzzy etc...)

Hope this helps!

Upvotes: 1

Related Questions