Here is a short intro on using elasticsearch filters with java.

Combining filters

        XContentFilterBuilder filter1 = FilterBuilders.orFilter(
				FilterBuilders.termsFilter("disclaimer","searchKeyword"),
				FilterBuilders.termsFilter("foootnote", "searchKeyword"))
				.filterName(filter11);
//filter name can be used later to find matched filter
		XContentFilterBuilder filter2 = FilterBuilders.orFilter(
				FilterBuilders.termsFilter("senderNumber","searchKeyword"),
				FilterBuilders.termsFilter("receiverNumber", "searchKeyword"))
				.filterName(filter22);

        XContentFilterBuilder filter33 = FilterBuilders.orFilter(
        		FilterBuilders.termFilter("messageText", "searchKeyword"),
        		FilterBuilders.termFilter("messageSubject", "searchKeyword").
        		filterName(filter33);

        // These filter can then be combined using one more filter
        XContentFilterBuilder messageFilter = FilterBuilders.orFilter(filter1, filter2, filter3);



Checking for presence of a keyword( i.e. NOT NULL)

Here’s an example in which a filter is created to check for the existence of a keyword “hiddenTag”.

XContentFilterBuilder existsFilter = FilterBuilders.notFilter(
        		FilterBuilders.missingFilter("hiddenTag"));
//This filter can then be combined with other filters like below
messageFilter = FilterBuilders.andFilter(messageFilter, notExistsFilter);



Pagination

By default only 10 results are returned. To return more results and apply pagination we can build our query like this :

qb = QueryBuilders.filteredQuery(qb, messageFilter);
builder.setQuery(qb).setFrom((pageNumber-1)*pageSize).setSize(pageSize);
Advertisements