我正在使用 _id 从弹性搜索中搜索记录,并且能够从弹性搜索中获取记录。但现在我想使用通配符基于 _source(来自 _source 的任何字段)进行搜索。我不确定如何为此构建我的查询。有这方面的文件吗?
请在下面找到我的代码,可以根据_id查询弹性搜索。
我正在使用弹性搜索 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"
}
}
]
}