Search code examples
elasticsearchliferay

Liferay Elastic Search: Query fields using StringQuery


I need to query two fields from elastic search using query_string: e.g. name and age.

It works if I do it via the following query directly to Liferay's Elastic Search:

{
  "query": {
    "bool": {
      "must": [ 
        { "match": { "recordSetId": "123" }}, 
        { "query_string": 
            { 
                "query": "Maximil*",
                "fields": ["name", "age"]
            }
        }
      ]
    }
  }
}

Does anyone know how I can send the above query from Liferay Java Code? I would need something like:

StringQuery query = queries.string(searchTerms);
query.setFields(); // this does not exist...

Solution

  • SearchContext searchContext = new SearchContext();
    searchContext.setStart(QueryUtil.ALL_POS);
    searchContext.setEnd(QueryUtil.ALL_POS);
    searchContext.setUserId(userId);
    searchContext.setEntryClassNames("Enter the name of the class you want to get data from");
    

    (Like : "JournalArticle.class.getName()")

    BooleanQuery query = new BooleanQueryImpl();
    query.add(new TermQueryImpl("name", "Maximil*",BooleanClauseOccur.MUST);
    query.add(new TermQueryImpl("age","Maximil*",BooleanClauseOccur.MUST);
    
    Hits hits = IndexSearcherHelperUtil.search(searchContext, query);
    List<Document> document = hits.toList();