gpt4 book ai didi

java - ElasticSearch 按 _source 字段搜索

转载 作者:行者123 更新时间:2023-12-02 22:22:23 24 4
gpt4 key购买 nike

我需要实现一个搜索引擎。像谷歌/雅虎搜索一样,在搜索组件中,如果输入任何键,它应该找到匹配项并显示。为此,我创建了与 Elasticsearch 集成的 Spring Boot 项目。

我使用 logstash 在 Elasticsearch 中为我的 Oracle 数据库创建了索引。通过使用下面的代码,我能够根据 Elasticsearch 索引 ID 获取记录。

private final String INDEX = "bookdata";
private final String TYPE = "books";

public Map<String, Object> getBookById(String id){
GetRequest getRequest = new GetRequest(INDEX, TYPE, id);
GetResponse getResponse = null;
try {
getResponse = restHighLevelClient.get(getRequest);
} catch (java.io.IOException e){
e.getLocalizedMessage();
}
Map<String, Object> sourceAsMap = getResponse.getSourceAsMap();
return sourceAsMap;
}

以上代码运行良好,能够根据ID 获取图书。但我必须知道这本书的作者或书名。

请在 Kibana 的 Elastic 搜索中找到我的索引文档

{
"took": 34,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 3,
"max_score": 1,
"hits": [
{
"_index": "bookdata",
"_type": "books",
"_id": "72c58f1a-7bfe-41be-a7f4-ee0aca3f4cf4", //able to search by ID
"_score": 1,
"_source": {
"id": "72c58f1a-7bfe-41be-a7f4-ee0aca3f4cf4",
"title": "Java Always", // want to search by Title
"author": "JournalDev", // or want to search by author
"price": 99.1
}
}
}

不是很清楚,如何在书的作者或书名中搜索。

最佳答案

您需要使用 search API而不是 Get API。

// 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("author", "JournalDev");
searchSourceBuilder.query(matchQueryBuilder);
searchRequest.source(searchSourceBuilder);

// send the request
SearchResponse searchResponse = restHighLevelClient.search(searchRequest);

// read the response
SearchHit[] searchHits = searchResponse.getHits().getHits();
for (SearchHit hit : searchHits) {
// get each hit as a Map
Map<String, Object> sourceAsMap = hit.getSourceAsMap();
String documentTitle = (String) sourceAsMap.get("title");
...
}

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

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