0
votes

If I have a Lucene query string

"field1:value1 myField:aValue"

Is there a way to let Lucene parse this so I can get term queries?
I ultimately want to be able to get the field names and their values back to my viewdata so I can fill them in my textboxes on post back.

2

2 Answers

2
votes

lucene's QueryParser will convert that string into a BooleanQuery containing two TermQuery clauses. You'll need to use the getClauses method of BooleanQuery to get the term queries.

2
votes

I faced similar requirement, but the query can be generic. Came up with the below method (Implemented in java). Full code https://github.com/atulsm/Test_Projects/blob/master/src/TestLuceneQueryStringFields.java

private static Set<String> calculateQueryFieldsRecursively(Query query) throws ParseException{
    Set<String> fields = new HashSet<String>();

    if(query instanceof TermQuery){
        TermQuery tQuery = (TermQuery)query;            
        Term term = tQuery.getTerm();
        fields.add(term.field());
    } else if(query instanceof BooleanQuery){
        BooleanQuery bQuery = (BooleanQuery)query;
        List<BooleanClause> clauses = bQuery.clauses();
        for(BooleanClause clause: clauses){
            Query innerQuery = clause.getQuery();
            Set<String> innerFields = calculateQueryFieldsRecursively(innerQuery);
            if(innerFields == null){
                return null;
            }else{
                fields.addAll(innerFields);
            }
        }
    } else { //TODO support more lucene query types
        return null;
    }   
    return fields;
}