基于源字段搜索的java查询弹性搜索
我使用_id从弹性搜索中搜索记录,并且我能够从弹性搜索中获取记录。但是现在我想使用通配符基于_source(来自_source的任何字段)进行搜索。我不确定如何为此构建我的查询。有关于这方面的文件吗
请在下面找到我的代码,我可以根据_id查询弹性搜索
Am使用弹性搜索6.2.3版本
public Product getProductById(String id){
String[] includes = new String[]{id};
String[] excludes = Strings.EMPTY_ARRAY;
GetRequest getRequest = new GetRequest(INDEX, TYPE, SOURCE);
getRequest.routing(id);
GetResponse getResponse = null;
try {
getResponse = restHighLevelClient.get(getRequest);
} catch (java.io.IOException e){
e.getLocalizedMessage();
}
//GetResponse getResponse = null;
// create the search request
SearchRequest searchRequest = new SearchRequest(INDEX);
searchRequest.types(TYPE);
// create the match query on the author field
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("_id", id);
searchSourceBuilder.query(matchQueryBuilder);
searchRequest.source(searchSourceBuilder);
// send the request
SearchResponse searchResponse = null;
try {
searchResponse = restHighLevelClient.search(searchRequest);
} catch (IOException e) {
e.getLocalizedMessage();
}
// read the response
String productName = null;
Product product = null;
SearchHit[] searchHits = searchResponse.getHits().getHits();
for (SearchHit hit : searchHits) {
// get each hit as a Map
Map<String, Object> sourceAsMap = hit.getSourceAsMap();
product=new Product();
product.setName(sourceAsMap.get("name").toString());
}
Gson gson=new Gson();
JSONObject productJSON = null;
String prodStr=gson.toJson(product);
try {
productJSON=new JSONObject(prodStr);
} catch (JSONException e) {
e.printStackTrace();
}
return product;
}
请在弹性搜索中查找可用记录。在这里,我想根据_source字段搜索此记录。例如:基于code
的搜索
{
"took":50,
"timed_out":false,
"_shards":{
"total":5,
"successful":5,
"skipped":0,
"failed":0
},
"hits":{
"total":1,
"max_score":1.0,
"hits":[
{
"_index":"my_index",
"_type":"doc",
"_id":"MUC8GmMBRU-f7c0A8LUY",
"_score":1.0,
"_source":{
"@version":"1",
"vendor_id":1,
"name":"prod7",
"code":"abc1234",
"catalog_id":343,
"is_visible":1,
"@timestamp":"2018-05-01T08:06:16.642Z"
}
}
]
}
# 1 楼答案
只需更换这一行
用这个