我正在尝试对全文查询进行搜索
如果我得到http:// localhost:8080 / search / query / tes
它应显示用户姓氏或名字包含tes。我实现了它们。但是出了点问题,它说找不到匹配(找不到JSONObject [“hits”])。
使用Elasticsearch的Spring Boot
@Service
public class SearchService implements ISearchService {
@Value("${api.elasticsearch.uri}")
private String elasticSearchUri;
@Value("${api.elasticsearch.search}")
private String elasticSearchSearchPrefix;
private static final Logger LOGGER = LoggerFactory.getLogger(SearchService.class);
@Override
public ResultQuery searchFromQuery(String query) throws IOException {
String body = HelperFunctions.buildMultiIndexMatchBody(query);
return executeHttpRequest(body);
}
/**
* Fetch resultQuery from elastic engine for the given body
*
* @param body String
* @return ResultQuery
* @throws IOException IOException
*/
private ResultQuery executeHttpRequest(String body) throws IOException{
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
ResultQuery resultQuery = new ResultQuery();
HttpPost httpPost = new HttpPost(HelperFunctions.buildSearchUri(elasticSearchUri
, "", elasticSearchSearchPrefix));
httpPost.setHeader(Accept, application/json);
httpPost.setHeader(Content-type, application/json);
try {
httpPost.setEntity(new StringEntity(body, UTF-8));
HttpResponse response = httpClient.execute(httpPost);
String message = EntityUtils.toString(response.getEntity());
JSONObject myObject = new JSONObject(message);
if(myObject.getJSONObject(hits)
.getInt(total) != 0){
resultQuery
.setElements(myObject
.getJSONObject(hits)
.getJSONArray(hits)
.toString());
resultQuery
.setNumberOfResults(myObject.getJSONObject(hits)
.getInt(total));
resultQuery.setTimeTook((float) ((double) myObject.getInt(took) / 1000));
} else {
resultQuery.setElements(null);
resultQuery.setNumberOfResults(0);
resultQuery.setTimeTook((float) ((double) myObject.getInt(took) / 1000));
}
} catch (IOException | JSONException e) {
LOGGER.error("Error while connecting to elastic engine --> {}", e.getMessage());
resultQuery.setNumberOfResults(0);
}
return resultQuery;
}
}
}
最佳答案
是认证问题。我在开始连接basicauth(user:pass)时创建了一个服务,但是由于某种原因,该服务在该json REST页面上没有标题。所以我添加了 token 头,voilà它起作用了。
关于spring - 找不到Elasticsearch Spring JSONObject [“hits”],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63069459/