gpt4 book ai didi

java - 使用Java从Elasticsearch 7.3的字段进行查询

转载 作者:行者123 更新时间:2023-12-03 02:20:26 27 4
gpt4 key购买 nike

我的以下代码可以正常工作并返回文档。我想基于文档中的only one field进行搜索,并将从所有文档中返回该字段的值。

        RestHighLevelClient client;

QueryBuilder matchQueryBuilder = QueryBuilders.queryStringQuery("elon");
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(matchQueryBuilder);
sourceBuilder.from(0);
sourceBuilder.size(10);
sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
SearchRequest searchRequest = new SearchRequest(ELASTIC_SEARCH_INDEX);
searchRequest.source(sourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
我需要它仅搜索 Name字段,并从此搜索返回的所有文档中返回该字段的值。
假设我查询 Elon,它应该响应 List<String>“莉莉·伊隆麝香”,“帕克·伊隆”,伊隆·麝香77”而忽略其他字段。
映射
{
students: {
mappings: {
properties: {
students: {
properties: {
courseTitle: {
type: "text",
fields: {
keyword: {
type: "keyword",
ignore_above: 256
}
}
},
courseCode: {
type: "text",
fields: {
keyword: {
type: "keyword",
ignore_above: 256
}
}
},
name: {
type: "text",
fields: {
keyword: {
type: "keyword",
ignore_above: 256
}
}
},
courseGrade: {
type: "text",
fields: {
keyword: {
type: "keyword",
ignore_above: 256
}
}
}
}
}
}
}
}
}
样本文件
students: [
{
courseCode: " HM101",
courseTitle: "ICP",
courseGrade: "A"
},
{
courseCode: " CS101",
courseTitle: "electronice",
courseGrade: "B+"
},
{
name: "elon musk"
}]

最佳答案

I need it to search only Name field and return the value of that fieldfrom all documents that returned in this search.


不是简单明了的。您需要按以下方式更改查询字符串以仅处理名称字段。
JAVA方式:
QueryBuilder matchQueryBuilder = 
QueryBuilders.queryStringQuery("elon").defaultField("name");

String[] includeFields = new String[] {"name"};
String[] excludeFields = new String[] {"user"};
sourceBuilder.fetchSource(includeFields, excludeFields);
平原:
  {
"_source":
["name"],
"query": {
"query_string" : {
"query" : "name:elon"

}
}

}
您可以执行 source controlling in code,希望您仅对 query_string方式感兴趣。如果您愿意接受其他方式,可以使用 this
然后要转换为 List<String>,您需要迭代响应并将其添加到 List
SearchHits hits = searchResponse.getHits();
SearchHit[] searchHits = hits.getHits();
List<String> names = new ArrayList<String>();
for (SearchHit hit : searchHits) {
Map<String, Object> sourceAsMap = hit.getSourceAsMap();
names.add(sourceAsMap.get("name"));
}

关于java - 使用Java从Elasticsearch 7.3的字段进行查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62502315/

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