gpt4 book ai didi

java - 基于_source字段搜索查询elasticsearch

转载 作者:行者123 更新时间:2023-12-02 11:12:48 30 4
gpt4 key购买 nike

正在使用 _id 从 Elasticsearch 中搜索记录,并且能够从 Elasticsearch 中获取记录。但现在我想使用通配符基于 _source (来自 _source 的任何字段)进行搜索。我不确定如何为此构建我的查询。有这方面的文档吗?

请在下面找到我的代码,我能够根据_id查询 Elasticsearch 。

我使用的是elasticsearch 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;
}

请在elasticsearch中找到可用的记录。这里我想根据 _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"
}
}
]
}

最佳答案

只需替换这一行

MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("_id", id); 

用这个

MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("code", "abc1234"); 

关于java - 基于_source字段搜索查询elasticsearch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50501144/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com