Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring-data-elasticsearch search for specific fields in multiple indices

I try to search specific fields in multiple indices. I have two indices country and region. Both of the indices have a Field called name.

I am able to specify my field name and my indices in my query using elasticsaerchTemplate:

@Override
public Page<SearchHit> searchAllTest(String text) {
    QueryBuilder queryBuilder = QueryBuilders.boolQuery()
            .should(QueryBuilders.queryStringQuery(text).field("name"));

    NativeSearchQuery nativeSearchQuery = new NativeSearchQueryBuilder()
            .withQuery(queryBuilder)
            .withIndices("region", "country").build();

    ResultsExtractor<Page<SearchHit>> rs = new ResultsExtractor<Page<SearchHit>>() {

        @Override
        public Page<SearchHit> extract(SearchResponse response) {
            List<SearchHit> hits = Arrays.asList(response.getHits().getHits());
            return new PageImpl<SearchHit>(hits, PageRequest.of(0, 10), response.getHits().getTotalHits());
        }

    };
    return elasticsearchTemplate.query(nativeSearchQuery, rs);
}

This code works and searches for the field name in both of the indices. But I would like to specify the field name in index region and give for example a boost.

In simple words:

  • Field name belongs to index region and get a boost.
  • Field name belongs to index country and get no boost.

Is there a way to specify a field for a particular index?

like image 757
Patrick Avatar asked Feb 21 '18 13:02

Patrick


Video Answer


1 Answers

Try to use withIndexBoost method:

NativeSearchQuery nativeSearchQuery = new NativeSearchQueryBuilder()
        .withQuery(queryBuilder)
        .withIndicesBoost(Arrays.asList(new IndexBoost[] {new IndexBoost("region", 2.0f)}))
        .withIndices("region", "country").build();
like image 89
Mike Shauneu Avatar answered Sep 17 '22 22:09

Mike Shauneu