在多个索引中搜索时,如何在搜索结果中获取索引名称?

时间:2020-09-22 12:24:44

标签: spring-data-elasticsearch

elasticsearch的“ multi-match”查询在搜索多个索引时会返回搜索结果中索引的名称。

GET localhost:9200/users,locations/_search

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

响应包含_index字段,该字段说明了得出结果的索引

"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": "xyz@gmail.com",
      "@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": "abc@gmail.com",
      "@timestamp": "2020-09-22T09:57:23.121Z"
    }
  }
]

spring-data-elasticsearch中用于hits的类是SearchHits,而SearchHit的字段idcontentscore获得与Elasticsearch查询类似的数据。但是它不包含用于存储_index字段信息的相关字段。

是否支持?我需要根据哪个客户端应用程序将生成一些URL来发送搜索命中类型(_index名称)。

这是我使用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;
}

1 个答案:

答案 0 :(得分:1)

这是通过https://jira.spring.io/browse/DATAES-848实现的,并且自里程碑版本4.1.M1开始是4.1版本。

有关如何使用RC或里程碑版本的信息,请访问https://github.com/spring-projects/spring-data-elasticsearch#maven-configuration