How to create nested boolean query with lucene API (a AND (b OR c))?

前端 未结 2 853
深忆病人
深忆病人 2020-12-29 10:05

I have an indexed object with three fields (userId, title, description). I want to find all objects of a specific user where the title OR the description contains a given ke

相关标签:
2条回答
  • 2020-12-29 10:43

    I think that it will be something like this:

    TermQuery userQuery = new TermQuery(new Term("user_id", u.getId()+""));
    
    BooleanQuery orQuery = new BooleanQuery();
    orQuery.add(new BooleanClause(name_query, Occur.SHOULD));
    orQuery.add(new BooleanClause(desc_query, Occur.SHOULD));
    
    BooleanQuery andQuery = new BooleanQuery();
    andQuery.add(new BooleanClause(userQuery , Occur.MUST));
    andQuery.add(new BooleanClause(orQuery, Occur.MUST));
    
    0 讨论(0)
  • 2020-12-29 11:04

    I believe that you'll need to use the Query.mergeBooleanQueries method in order to create a single query that is the effective OR of the first two.

    So something like this at line 3:

    Query nameOrDescQuery = Query.mergeBooleanQueries(new Query[] { nameQuery, descQuery });
    

    and then create a new BooleanClause over this, rather than the individual clauses.

    This should ensure you get the OR logic on your name/desc filters rather than the current AND logic.

    0 讨论(0)
提交回复
热议问题