>  기사  >  Java  >  ES 구문 분석 검색 반환 필드를 통합하는 SpringBoot 문제를 해결하는 방법

ES 구문 분석 검색 반환 필드를 통합하는 SpringBoot 문제를 해결하는 방법

PHPz
PHPz앞으로
2023-05-16 08:13:071256검색

    1. 데이터 구조

    호텔 인덱스에 대한 인덱스 2:

    PUT /hotel/_doc/1
    {
      "title": "文雅酒店",
      "city": "青岛",
      "price": 556,
      "create_time": "20200418120000",
      "amenities": "浴池,普通停车场/充电停车场",
      "full_room": false,
      "location": {
        "lat": 36.083078,
        "lon": 120.37566
      },
      "praise": 10
    }
    
    PUT /hotel/_doc/2
    {
      "title": "金都嘉怡假日酒店",
      "city": "北京",
      "price": 337,
      "create_time": "20210315200000",
      "amenities": "wifi,充电停车场/可升降停车场",
      "full_room": false,
      "location": {
        "lat": 39.915153,
        "lon": 116.403
      },
      "praise": 60
    }
    
    PUT /hotel/_doc/1
    {
      "title": "文雅酒店",
      "city": "青岛",
      "price": 556,
      "create_time": "20200418120000",
      "amenities": "浴池,普通停车场/充电停车场",
      "full_room": false,
      "location": {
        "lat": 36.083078,
        "lon": 120.37566
      },
      "praise": 10
    }
    
    PUT /hotel/_doc/2
    {
      "title": "金都嘉怡假日酒店",
      "city": "北京",
      "price": 337,
      "create_time": "20210315200000",
      "amenities": "wifi,充电停车场/可升降停车场",
      "full_room": false,
      "location": {
        "lat": 39.915153,
        "lon": 116.403
      },
      "praise": 60
    }

    2. ElasticSearch는 클러스터의 모든 인덱스에 있는 모든 문서를 쿼리합니다.

     GET /hotel/_search
    {
      "took" : 499,
      "timed_out" : false,
      "_shards" : {
        "total" : 5,
        "successful" : 5,
        "skipped" : 0,
        "failed" : 0
      },
      "hits" : {
        "total" : {
          "value" : 2,
          "relation" : "eq"
        },
        "max_score" : 1.0,
        "hits" : [
          {
            "_index" : "hotel",
            "_type" : "_doc",
            "_id" : "2",
            "_score" : 1.0,
            "_source" : {
              "title" : "金都嘉怡假日酒店",
              "city" : "北京",
              "price" : 337,
              "create_time" : "20210315200000",
              "amenities" : "wifi,充电停车场/可升降停车场",
              "full_room" : false,
              "location" : {
                "lat" : 39.915153,
                "lon" : 116.403
              },
              "praise" : 60
            }
          },
          {
            "_index" : "hotel",
            "_type" : "_doc",
            "_id" : "1",
            "_score" : 1.0,
            "_source" : {
              "title" : "文雅酒店",
              "city" : "青岛",
              "price" : 556,
              "create_time" : "20200418120000",
              "amenities" : "浴池,普通停车场/充电停车场",
              "full_room" : false,
              "location" : {
                "lat" : 36.083078,
                "lon" : 120.37566
              },
              "praise" : 10
            }
          }
        ]
      }
    }

    3. 검색 요청에 걸린 시간(밀리초)

    took 값은 전체 검색 요청을 실행하는 데 걸린 시간(밀리초)을 알려줍니다.

    2. shards 쿼리에 참여하는 샤드의 총 개수 took 值告诉我们执行整个搜索请求耗费了多少毫秒。

    2. shards 查询中参与分片的总数

    _shards 部分告诉我们在查询中参与分片的总数,以及这些分片成功了多少个失败了多少个。正常情况下我们不希望分片失败,但是分片失败是可能发生的。如果我们遭遇到一种灾难级别的故障,在这个故障中丢失了相同分片的原始数据和副本,那么对这个分片将没有可用副本来对搜索请求作出响应。假若这样,Elasticsearch 将报告这个分片是失败的,但是会继续返回剩余分片的结果。

    3. timed_out 查询是否超时

    timed_out 值告诉我们查询是否超时。默认情况下,搜索请求不会超时。

    4. hits 表示搜索结果

    返回结果中最重要的部分是 hits ,它包含 total 字段来表示匹配到的文档总数,并且一个 hits

    _shards 부분은 쿼리에 참여하는 샤드의 총 개수와 이 샤드 중 성공한 개수와 실패한 개수를 알려줍니다. 일반적으로 우리는 샤딩이 실패하는 것을 원하지 않지만 샤딩 실패가 발생할 수 있습니다. 동일한 샤드의 원본 데이터와 복제본이 손실되는 치명적인 오류가 발생하는 경우 검색 요청에 응답할 수 있는 해당 샤드의 복제본이 없게 됩니다. 그렇다면 Elasticsearch는 이 샤드를 실패로 보고하지만 나머지 샤드에 대한 결과를 계속 반환합니다.

    3.timed_out 쿼리 시간 초과 여부

    timed_out 값은 쿼리 시간 초과 여부를 알려줍니다. 기본적으로 검색 요청은 시간 초과되지 않습니다.

    4. 조회수는 검색 결과를 나타냅니다.

    반환된 결과에서 가장 중요한 부분은 일치하는 문서의 총 수를 나타내는 total 필드를 포함하는 조회수입니다. a hits 배열에는 쿼리 결과의 처음 10개 문서가 포함됩니다. 검색 결과를 구문 분석할 때 일반적으로 다음 필드에 주의해야 합니다.

    hits.total.value: 일치하는 문서의 총 수입니다.

    hits.max_score: 쿼리와 일치하는 문서의 _score 최대값입니다.

    hits.hits: 일치하는 문서 목록입니다.

    hits.hits._source: 일치하는 문서의 원시 데이터입니다.

    hits.hits._score: 일치하는 문서의 점수입니다. 문서가 쿼리와 얼마나 잘 일치하는지 측정합니다. 기본적으로 가장 관련성이 높은 문서 결과가 먼저 반환됩니다. 즉, 반환된 문서는 점수별로 내림차순으로 정렬됩니다.

    hits.hits.highlight: 일치하는 문서의 정보를 강조 표시합니다.

    4. SpringBoot는 ElasticSearch를 통합하여 검색 결과를 얻습니다

    @Slf4j
    @Service
    public class ElasticSearchImpl {
    
        @Autowired
        private RestHighLevelClient restHighLevelClient;
    
        public void searchUser() throws IOException {
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            SearchRequest searchRequest = new SearchRequest(new String[]{"hotel"},searchSourceBuilder);
            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
    
            TimeValue took = searchResponse.getTook();
            System.out.println("took = " + took);
    
            // 搜索结果
            SearchHits searchHits = searchResponse.getHits();
    
            // hits.total.value:匹配的文档总数
            TotalHits totalHits = searchHits.getTotalHits();
            long value = totalHits.value;
            System.out.println("value = " + value);
    
            // hits.max_score:与查询所匹配文档的_score的最大值
            float maxScore = searchHits.getMaxScore();
            System.out.println("maxScore = " + maxScore);
    
            // hits.hits:匹配的文档列表
            SearchHit[] hits = searchHits.getHits();
            for (SearchHit hit : hits) {
                // hits.hits._source:匹配的文档的原始数据
                String sourceAsString = hit.getSourceAsString();
                System.out.println("sourceAsString = " + sourceAsString);
    
                //  hits.hits._id:匹配的文档的id
                String id = hit.getId();
                System.out.println("id = " + id);
    
                Map<String, DocumentField> fields = hit.getFields();
                System.out.println("fields = " + fields);
    
                String index = hit.getIndex();
                System.out.println("index = " + index);
    
                float score = hit.getScore();
                System.out.println("score = " + score);
            }
            System.out.println(searchResponse);
    
        }
    }
    
    @Slf4j
    @Service
    public class ElasticSearchImpl {
    
        @Autowired
        private RestHighLevelClient restHighLevelClient;
    
        public void searchUser() throws IOException {
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            SearchRequest searchRequest = new SearchRequest(new String[]{"hotel"},searchSourceBuilder);
            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
    
            TimeValue took = searchResponse.getTook();
            System.out.println("took = " + took);
    
            // 搜索结果
            SearchHits searchHits = searchResponse.getHits();
    
            // hits.total.value:匹配的文档总数
            TotalHits totalHits = searchHits.getTotalHits();
            long value = totalHits.value;
            System.out.println("value = " + value);
    
            // hits.max_score:与查询所匹配文档的_score的最大值
            float maxScore = searchHits.getMaxScore();
            System.out.println("maxScore = " + maxScore);
    
            // hits.hits:匹配的文档列表
            SearchHit[] hits = searchHits.getHits();
            for (SearchHit hit : hits) {
                // hits.hits._source:匹配的文档的原始数据
                String sourceAsString = hit.getSourceAsString();
                System.out.println("sourceAsString = " + sourceAsString);
    
                //  hits.hits._id:匹配的文档的id
                String id = hit.getId();
                System.out.println("id = " + id);
    
                Map<String, DocumentField> fields = hit.getFields();
                System.out.println("fields = " + fields);
    
                String index = hit.getIndex();
                System.out.println("index = " + index);
    
                float score = hit.getScore();
                System.out.println("score = " + score);
            }
            System.out.println(searchResponse);
    
        }
    }
    took=2ms
    value = 2
    maxScore = 1.0
    
    sourceAsString = {"title":"金都嘉怡假日酒店","city":"北京","price":337,"create_time":"20210315200000","amenities":"wifi,充电停车场/可升降停车场","full_room":false,"location":{"lat":39.915153,"lon":116.403},"praise":60}
    id = 2
    fields = {}
    index = hotel
    score = 1.0
    
    sourceAsString = {"title":"文雅酒店","city":"青岛","price":556,"create_time":"20200418120000","amenities":"浴池,普通停车场/充电停车场","full_room":false,"location":{"lat":36.083078,"lon":120.37566},"praise":10}
    id = 1
    fields = {}
    index = hotel
    score = 1.0
    {
        "took": 2,
        "timed_out": false,
        "_shards": {
            "total": 5,
            "successful": 5,
            "skipped": 0,
            "failed": 0
        },
        "hits": {
            "total": {
                "value": 2,
                "relation": "eq"
            },
            "max_score": 1.0,
            "hits": [
                {
                    "_index": "hotel",
                    "_type": "_doc",
                    "_id": "2",
                    "_score": 1.0,
                    "_source": {
                        "title": "金都嘉怡假日酒店",
                        "city": "北京",
                        "price": 337,
                        "create_time": "20210315200000",
                        "amenities": "wifi,充电停车场/可升降停车场",
                        "full_room": false,
                        "location": {
                            "lat": 39.915153,
                            "lon": 116.403
                        },
                        "praise": 60
                    }
                },
                {
                    "_index": "hotel",
                    "_type": "_doc",
                    "_id": "1",
                    "_score": 1.0,
                    "_source": {
                        "title": "文雅酒店",
                        "city": "青岛",
                        "price": 556,
                        "create_time": "20200418120000",
                        "amenities": "浴池,普通停车场/充电停车场",
                        "full_room": false,
                        "location": {
                            "lat": 36.083078,
                            "lon": 120.37566
                        },
                        "praise": 10
                    }
                }
            ]
        }
    }

    5. ElasticSearch 검색 결과에 대한 인터뷰 질문

    1. ElasticSearch 검색 결과의 _score 필드는 무엇을 의미합니까?

    답변: _score 필드는 일치하는 문서의 관련성 점수를 나타냅니다. 점수가 높을수록 일치 정도가 높습니다.

    2. ElasticSearch 검색 결과의 하이라이트 필드는 무엇을 의미하나요?

    답변: 하이라이트 필드는 일치하는 문서에서 하이라이트된 필드와 하이라이트된 내용을 나타냅니다.

    3. ElasticSearch 검색 결과의 총 문서 수를 얻는 방법은 무엇입니까?

    답변: Hits.total.value 필드를 통해 일치하는 문서의 총 개수를 얻을 수 있습니다.

    4. ElasticSearch 검색 결과에서 일치하는 문서 목록을 가져오는 방법은 무엇입니까?

    답변: Hits.hits 필드를 통해 일치하는 문서 목록을 얻을 수 있습니다.

    5. ElasticSearch 검색 결과에서 일치하는 문서의 원본 데이터를 얻는 방법은 무엇입니까?

    답변: Hits.hits._source 필드를 통해 일치하는 문서의 원본 데이터를 얻을 수 있습니다.

    6. ElasticSearch 검색 결과에서 일치하는 문서의 강조된 정보를 얻는 방법은 무엇입니까?

    답변: Hits.hits.highlight 필드를 통해 일치하는 문서의 하이라이트 정보를 얻을 수 있습니다. 🎜🎜7. ElasticSearch 검색 결과의 _shards 필드는 무엇을 의미하나요? 🎜🎜답변: _shards 필드는 총 샤드 수, 성공한 샤드 수, 건너뛴 샤드 수, 실패한 샤드 수 등 검색과 관련된 샤드 정보를 나타냅니다. 🎜🎜8. ElasticSearch 검색 결과의 take 필드는 무엇을 의미하나요? 🎜🎜답변: take 필드는 검색 시간을 밀리초 단위로 나타냅니다. 🎜

    위 내용은 ES 구문 분석 검색 반환 필드를 통합하는 SpringBoot 문제를 해결하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

    성명:
    이 기사는 yisu.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제