如何从elasticsearch获取_id

时间:2018-03-14 06:58:36

标签: java json elasticsearch

我已经创建了一个searchResponse来通过java api从elasticsearch获取数据。

数据是:

{
"took": 2,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
 },
"hits": {
"total": 2,
"max_score": 1,
"hits": [
  {
    "_index": "testmerge2",
    "_type": "final",
    "_id": "AWGyd4lYPXZPzBg2Ogp1",
    "_score": 1,
    "_source": {
      "user": "kimchy",
      "postDate": "2013-01-30",
      "message": "trying out Elasticsearch",
       }
}

获取数据的Java代码:

TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
            .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));

SearchResponse sr1 = client.prepareSearch("Index").setQuery(QueryBuilders.matchQuery("XXX", XXX)).get();

我的问题是:如何从点击中检索“_id”字段?

1 个答案:

答案 0 :(得分:0)

像这样:

SearchResponse sr1 = client.prepareSearch("Index").setQuery(QueryBuilders.matchQuery("XXX", XXX)).get();
for (SearchHit searchHit : sr1.getHits().getHits()) {
    String id = searchHit.getId();
}