先做一个简单的针对ElasticSearch的查询demo:
@GetMapping("/es")
@ApiOperation("ES整合测试")
public Map<String,Object> getES(String indexName,String typeName){
Map<String,Object> result = new HashMap<>();
try {
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.termQuery("_id","2a6f6ef3-8bc5-4b14-b3b6-ed4252a601e8"));
Search search =new Search.Builder(searchSourceBuilder.toString()).addIndex("ceshi1").addType("data").build();
JestResult jestResult = jestClient.execute(search);
System.out.println(jestResult.toString());
result.put("result",jestResult.toString());
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
启动项目访问接口查询一条记录,我在代码中使用查询结果jestResult调用toString()方法,打印到了控制台,结果如下:
Result: {"took":1,"timed_out":false,"_shards":{"total":5,"successful":5,"skipped":0,"failed":0},
"hits":{"total":1,"max_score":1.0,"hits":[{"_index":"ceshi1","_type":"data","_id":"2a6f6ef3-8bc5-4b14-b3b6-ed4252a601e8",
"_score":1.0,"_source":{"age1":"12","name2":"8","name":"12","age2":"里五","ID":"里五1","name1":"12","age":"里五"}}]}},
isSucceeded: true, response code: 200, error message: null
刚学习ElasticSearch的时候我直接把这个结果放到JSON解析工具中去解析,想看看格式化后的结果,但是格式化工具却报错了: 不知道为什么,总觉得返回的应该是个JSON数据,然后就去研究了下JestResult,看了源码之后才知道JestResult重写了toString()方法: 可以看到JestResult这个类重写了toString()方法,在重写的toString()方法中给查询结果包了一层,改动如下: ①给查询结果添加了isSucceeded属性,表示是否查询成功 ②给查询结果添加了response code属性,表示查询结果状态码,200表示查询成功 ③给查询结果添加了error message属性,表示查询失败后的报错信息
也就是在前面restResult.toString()后的字符串尾部几个属性值: 其实真正的查询结果在这里:
jestResult.getJsonString()
这样就能拿到结果:
|