Message Boards

Search Filter BooleanFilter help

Uwe Peters, modified 2 Years ago.

Search Filter BooleanFilter help

New Member Posts: 22 Join Date: 11/24/20 Recent Posts

Hello there,

I am trying to add a filter with a condition to my search in Liferay 7.2 CE (Elasticsearch (Embedded), Client-Version: 7.3.0, liferay (7.3.0)). 
Currently I am trying to add the filter in the overridden postProcessContextBooleanFilter method from my IndexerPostProcessor class of my model.

To explain my problem I came up with this example.

Result that should be filtered:
Object1 = {type=1, status="in_progress"}
Object2 = {type=1, status="open"}
Object3 = {type=1, status="finished"}
Object4 = {type=2, status="open"}
Object5 = {type=3, status="in_progress"}

The filter that I want to achieve:
find all objects that are of type = '1' AND status = 'in progress' 

find all other objects that are not type = '1' without checking the status 

My filter should return:

[Object1, Object4, Object5]

I dont know how to achieve this in my postProcessContextBooleanFilter method.

What I have so far:

TermsFilter typeFilter = new TermsFilter("type");
filterDepartmentName.addValues("1");

TermsFilter statusFilter = new TermsFilter("status");
filterDepartmentName.addValues("in_progress");

booleanFilter.add(typeFilter, BooleanClauseOccur.MUST);
booleanFilter.add(statusFilter, BooleanClauseOccur.MUST);

This snippet above will return Object1 from my example. 
How do I add another Filter to return Object1 AND all other Objects that are not type=1?

thumbnail
Russell Bohl, modified 2 Years ago.

RE: Search Filter BooleanFilter help

Expert Posts: 291 Join Date: 2/13/13 Recent Posts

I think you'll need to model it with nested bool queries like this (this is roughly Elasticsearch DSL, but not perfect syntax):

{
  "query": {
    "bool" : {
        "should" : {
            "bool" : {
                "must" :  {
                    "term" : { "type" : "1" },
                    "term" : {"status" : "in_progress"}
                }
            },
            "bool" : {
                "must_not" : {
                    "term" : {"type" : "1"}
                }
            }
        }
    }
}

There's a default value of minimum_should_match=1 that's being leveraged to make the 2 should clauses operate like an OR condition. One of these 2 should clauses has to match for results to be returned. 

minimum_should_match docs from Elastic

Older but useful Elastic blog on boolean queries

Of course you then need to translate this into Liferay's Java Search API. But maybe that helps get you closer?

Additionally, it looks like you're using the older search APIs from portal-kernel? Like Elasticsearch, Liferay's newer APIs don't make API-level distinctions between Queries and Filters:

Liferay docs on Queries and filters