(JAVA,Elasticsearch)如何从SearchResponse获取字段?

时间:2018-11-20 11:06:44

标签: java elasticsearch

我只是想知道如何从SearchResponse获取字段,这是查询的结果。

下面是我的查询:

{"size":99,"timeout":"10s","query":{"bool":{"filter":[{"bool":{"must":[{"range":{"LOG_GEN_TIME":{"from":"2018-11-01 12:00:01+09:00","to":"2018-11-01 23:59:59+09:00","include_lower":true,"include_upper":true,"boost":1.0}}},{"wrapper":{"query":"eyAiYm9vbCIgOiB7ICJtdXN0IiA6IFsgeyAidGVybSIgOiB7ICJBU1NFVF9JUCIgOiAiMTAuMTExLjI1Mi4xNiIgfSB9LCB7ICJ0ZXJtIiA6IHsgIkFDVElPTl9UWVBFX0NEIiA6ICIyIiB9IH0sIHsgInRlcm0iIDogeyAiRFNUX1BPUlQiIDogIjgwIiB9IH0gXSB9IH0="}}],"adjust_pure_negative":true,"boost":1.0}}],"adjust_pure_negative":true,"boost":1.0}},"_source":{"includes":["LOG_GEN_TIME","LOG_NO","ASSET_NO"],"excludes":[]},"sort":[{"LOG_GEN_TIME":{"order":"desc"}},{"LOG_NO":{"order":"desc"}}]}

当我查询此内容时,如下所示:

SearchResponse searchResponse = request.get();

我得到正确的结果:

{  

   "took":1071,
   "timed_out":false,
   "_shards":{  
      "total":14,
      "successful":14,
      "skipped":0,
      "failed":0
   },
   "_clusters":{  
      "total":0,
      "successful":0,
      "skipped":0
   },
   "hits":{  
      "total":2,
      "max_score":null,
      "hits":[  
         {  
            "_index":"log_20181101",
            "_type":"SEC",
            "_id":"1197132746951492963",
            "_score":null,
            "_source":{  
               "ASSET_NO":1,
               "LOG_NO":1197132746951492963,
               "LOG_GEN_TIME":"2018-11-01 09:46:28+09:00"
            },
            "sort":[  
               1541033188000,
               1197132746951492963
            ]
         },
         {  
            "_index":"log_20181101",
            "_type":"SEC",
            "_id":"1197132746951492963",
            "_score":null,
            "_source":{  
               "ASSET_NO":2,
               "LOG_NO":1197337264704454700,
               "LOG_GEN_TIME":"2018-11-01 23:00:06+09:00"
            },
            "sort":[  
               1541080806000,
               1197337264704454700
            ]
         }
      ]
   }
}

要使用此结果,我需要按字段和值进行映射。

enter image description here

我认为有一种方法可以将字段和值映射到'fields'参数,以便我们可以很好地使用它,但是我找不到。

我希望我可以这样使用结果:

SearchHit hit = ...
Map<String, SearchHitField> fields = hit.getFields();
String logNo = fields.get("LOG_NO").value();

而且看来这是常用的使用方法。

还是我误会了什么?请告诉我其他方法,是否有更好的方法。

任何评论将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:0)

我不清楚您要使用哪个客户端来查询Elastic。如果您正在使用Elasticsearch高级休息客户端,则可以遍历命中并获取源,可以使用hit.getSourceAsMap()获得字段的键值。

供您评论:

  • 首先创建一个与_source对应的POJO类(即索引属性;数据以弹性方式存储)
  • 使用hit.getSourceAsString()获取json格式的_source。
  • 使用jackson ObjectMapper将json映射到您的pojo

假设您创建了POJO类 AssetLog

SearchHit[] searchHits = searchResponse.getHits().getHits();
for (SearchHit searchHit : searchHits) {
      String hitJson = searchHit.getSourceAsString();
      ObjectMapper objectMapper = new ObjectMapper();
      AssetLog source = objectMapper.readValue(hitJson, AssetLog.class);
      //Store source to map/array
}

希望这会有所帮助。