Elastic Search

Ch06. 고급 검색 - 검색 결과 하이라이트하기

webmaster 2025. 9. 24. 16:30
728x90

하이라이트는 문서 검색 결과를 웹상에서 출력할 때 사용자가 입력한 검색어를 강조하는 기능이다.

Request

POST movie_highlighting/_search
{
  "query": {
    "match": {
      "title": "harry"
    }
  },
  "highlight": {
  	/*
    "pre_tags": {
    	"<strong>"
    },
    "post_tags":{
    	"</strong>"
    }
    */
    "fields": {
      "title": {}
    }
  }
}

Response

{
  "hits": {
    "total": 1,
    "max_score": 0.2876821,
    "hits": [
      {
        "_index": "movie_highlighting",
        "_type": "_doc",
        "_id": "1",
        "_score": 0.2876821,
        "_source": {
          "title": "Harry Potter and the Deathly Hallows"
        },
        "highlight": {
          "title": [
          	//"<strong>Harry</strong> Potter and the Deathly Hallows"
            "<em>Harry</em> Potter and the Deathly Hallows"
          ]
        }
      }
    ]
  }
}
  • 데이터를 검색할 때, highlight 옵션을 이용해 하이라이트를 수행할 필드를 지정하면, 검색 결과로 하이라이트 된 데이터의 일부가 함께 리턴된다.
  • 하이라이트 기능을 사용해서 검색어와 일치하는 단어를 <em> 태그로 감싼 결과를 볼 수 있다.
  • 원문의 내용이 많을 경우에는 하이라이트된 데이터를 중심으로 위아래에 위치한 문장의 일부만 제공된다.
  • <em> 태그가 아닌 별도 태그를 지정하고 싶다면 highlight 옵션 내부에 원하는 태그를 정의하면 된다.

 

728x90