Search code examples
spring-data-elasticsearch

When searching across multiple indices, how to get the index name in search results?


The 'multi-match' query from elasticsearch returns the name of the index inside the search result when searching across multiple indices.

GET localhost:9200/users,locations/_search

{
    "query":{
        "multi_match":{
            "query": "pus",
            "type": "bool_prefix",
            "fields":[
                "name",
                "name._2gram",
                "name._3gram"
            ]
        }
    }
}

The response contains _index field which tells about the index from which the results came up

"hits": [{
    "_index": "locations",
    "_type": "_doc",
    "_id": "418",
    "_score": 1.0,
    "_source": {
      "name": "pusan-kwangyokshi | korea republic of | asia",
      "@timestamp": "2020-09-21T07:12:34.432Z"
    }
  },
  {
    "_index": "users",
    "_type": "_doc",
    "_id": "4",
    "_score": 1.0,
    "_source": {
      "name": "Puspjer taojomi",
      "uniqueId": "skjhs-sklhjs125",
      "accountStatus": 1,
      "email": "[email protected]",
      "@timestamp": "2020-09-22T09:57:22.977Z"
    }
  },
  {
    "_index": "users",
    "_type": "_doc",
    "_id": "52",
    "_score": 1.0,
    "_source": {
      "name": "Puspa yabna",
      "uniqueId": "sjhslkj-ta18ynsarda5",
      "accountStatus": 1,
      "email": "[email protected]",
      "@timestamp": "2020-09-22T09:57:23.121Z"
    }
  }
]

The class used in spring-data-elasticsearch for hits is SearchHits and SearchHit has fields id, content, score for getting the similar data as from elasticsearch query. But it doesn't contain the relevant field for storing _index field info.

Is it supported yet? I need to send the search hit type(_index name) based on which client application will generate some URLs.

This is my search query using spring

final NativeSearchQuery query = new NativeSearchQuery(QueryBuilders.multiMatchQuery(q, "name", "name._2gram", "name._3gram").type(MultiMatchQueryBuilder.Type.BOOL_PREFIX));
IndexCoordinates indexCoordinates = IndexCoordinates.of("users","locations");

return operations.search(query, OutDto.class, indexCoordinates)
        .getSearchHits()
        .stream()
        .map(SearchHit::getContent)
        .collect(Collectors.toList());


//The DTO class
public class OutDto{
  private Integer id;
  private String uniqueId;
  private String name;
  private String index;
}

Solution

  • This was implemented with https://jira.spring.io/browse/DATAES-848 and is in the 4.1 release since milestone release 4.1.M1.

    Information about how to use RC or milestone versions can be found at https://github.com/spring-projects/spring-data-elasticsearch#maven-configuration