2

I am in reference to the NativeSearchQueryBuilder spring data elasticsearch.

What is the way to set a post_filter to a nativeSearchQuery?

It seems possible with the native elasticsearch search api: see here and as follows:

SearchResponse response = client.prepareSearch("index1", "index2")
        .setTypes("type1", "type2")
        .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
        .setQuery(QueryBuilders.termQuery("multi", "test"))             // Query
        .setPostFilter(FilterBuilders.rangeFilter("age").from(12).to(18))   // Filter
        .setFrom(0).setSize(60).setExplain(true)
        .execute()
        .actionGet();

But I haven't found any way to do it in Spring data elasticsearch.

1 Answer 1

4
+50

The post_filter is used implicitly when you call the ElasticsearchTemplate.queryForPage(SearchQuery query, Class<T> clazz) method. It will check if the SearchQuery parameter contains a filter and if it does, it will call setPostFilter() with that filter on the native SearchRequestBuilder.

So you can construct your query using the NativeSearchQueryBuilder like this:

private ElasticsearchTemplate elasticsearchTemplate;

SearchQuery searchQuery = new NativeSearchQueryBuilder()
    .withQuery(matchAllQuery())                     <--- your query
    .withFilter(termFilter("name", "somename"))     <--- your post filter
    .build();

Page<SampleEntity> sampleEntities =
    elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class);

Under the hood, ElasticsearchTemplate will set the post_filter with the above term filter on the name field.

Sign up to request clarification or add additional context in comments.

1 Comment

Definitely the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.