ElasticSearch按_source字段搜索

时间:2018-05-02 02:11:27

标签: java elasticsearch kibana

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

使用logstash我在弹性搜索中为我的Oracle数据库创建了索引。通过使用下面的代码,我可以根据弹性搜索索引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获取Book。但我必须写这本书的作者或标题。

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

{
  "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
        }
      }
}

我不太确定,如何搜索本书的作者或标题。

1 个答案:

答案 0 :(得分: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");
    ...
}