我已经使用 Spring 开发了一个 REST API 条目,它在 Elasticsearch 中进行搜索,现在我想返回 ES 找到的任何结果作为响应。我不关心搜索结果,也不知道其中的 JSON 结构。我只是想把它退还给客户。
我希望这样的事情能起作用:
@RequestMapping(value = "/search/{index:.*}", method = RequestMethod.GET) public void search(@PathVariable String index, @RequestParam Map allRequestParams, HttpServletResponse response) throws IOException { BoolQueryBuilder query = QueryBuilders.boolQuery(); for (Map.Entry entry : allRequestParams.entrySet()) { query.should(QueryBuilders.fuzzyQuery(entry.getKey(), entry.getValue())); } SearchResponse results = esClient.prepareSearch("nyc_visionzero") .setTypes("logs") .setQuery(query) .execute() .actionGet(); SearchHits hits = results.getHits(); hits.writeTo(response.getOutputStream()); }
但是最后一行有编译错误,因为两个 OutputStream 不兼容。所以我的问题是,将 Elasticsearch 的结果连接到 Spring 的响应中的最简单方法是什么?
最佳答案
您可以更改搜索方法的签名以返回字符串,然后直接将结果作为有效 JSON 返回,而不是尝试写入响应输出流。像这样的东西:
@RequestMapping(value = "/search/{index:.*}", method = RequestMethod.GET)
public String search(@PathVariable String index, @RequestParam Map allRequestParams, HttpServletResponse response)
throws IOException
{
BoolQueryBuilder query = QueryBuilders.boolQuery();
for (Map.Entry entry : allRequestParams.entrySet()) {
query.should(QueryBuilders.fuzzyQuery(entry.getKey(), entry.getValue()));
}
SearchResponse results = esClient.prepareSearch("nyc_visionzero")
.setTypes("logs")
.setQuery(query)
.execute()
.actionGet();
SearchHits hits = results.getHits();
// Replacing hits.writeTo(response.getOutputStream()); below
StringBuilder builder = new StringBuilder();
SearchHit[] hitsDatas = hits.hits();
int length = hitsDatas.length;
builder.append("[");
for (int i = 0; i < length; i++) {
if (i == length - 1) {
builder.append(hitsDatas[i].getSourceAsString());
} else {
builder.append(hitsDatas[i].getSourceAsString());
builder.append(",");
}
}
builder.append("]");
return builder.toString();
}
关于java - 如何在 Spring REST API 响应中连接 Elasticsearch 的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45111201/