본문 바로가기
WIKI 기술 지식 베이스

Using semantic highlighting

원문 보기 위키 갱신

출처: 문서

본문

시맨틱 하이라이팅 사용하기

시맨틱 하이라이팅은 쿼리의 의미를 바탕으로 문서 내에서 의미적으로 가장 관련성이 높은 문장이나 구절을 찾아내고 강조함으로써 검색 결과를 한층 좋게 만들어 줘요. 정확한 키워드 일치에 의존하는 기존 하이라이터와 달리, 시맨틱 하이라이팅은 머신러닝(ML) 모델을 사용해 텍스트 세그먼트의 맥락과 관련성을 이해해요. 이 덕분에 강조된 구절에 정확한 검색어가 없더라도 문서 안에서 가장 관련성 높은 정보를 정확히 짚어낼 수 있어요. 자세한 내용은 semantic 하이라이터 사용하기를 참고하세요.

이 튜토리얼에서는 neural search 쿼리와 함께 시맨틱 하이라이팅을 설정하고 사용하는 과정을 안내해요.

your_ 접두사로 시작하는 플레이스홀더는 여러분의 값으로 바꿔 주세요. {: .note}

사전 준비

로컬 기본 설정이 제대로 동작하도록 하려면 다음 클러스터 설정을 지정해 주세요:

PUT _cluster/settings
{
  "persistent": {
    "plugins.ml_commons.allow_registering_model_via_url": "true",
    "plugins.ml_commons.only_run_on_ml_node": "false",
    "plugins.ml_commons.model_access_control_enabled": "true"
  }
}

{% include copy-curl.html %}

URL에서 모델을 등록할 때는 소스가 신뢰할 수 있는 것인지 꼭 확인해 주세요. 신뢰할 수 없는 소스에서 모델을 로드하면 보안 위험이 생길 수 있어요. 자세한 내용은 신뢰할 수 없는 모델에 대한 PyTorch 보안 가이드라인을 참고하세요. {: .warning}

이 예제는 전용 ML 노드가 없는 간단한 설정을 사용하며, ML 노드가 아닌 노드에서 모델을 실행할 수 있게 해 줘요. 전용 ML 노드가 있는 클러스터에서는 성능 향상을 위해 "only_run_on_ml_node": "true"를 지정해 주세요. 자세한 내용은 ML Commons 클러스터 설정을 참고하세요.

1단계: 인덱스 생성하기

먼저 텍스트 데이터와 그에 대응하는 벡터 임베딩을 저장할 인덱스를 만들어요. 원본 콘텐츠를 위한 text 필드와 임베딩을 위한 knn_vector 필드가 필요해요:

PUT neural-search-index
{
  "settings": {
    "index.knn": true
  },
  "mappings": {
    "properties": {
      "text": {
        "type": "text"
      },
      "text_embedding": {
        "type": "knn_vector",
        "dimension": 384, 
        "method": {
          "name": "hnsw",
          "space_type": "l2",
          "engine": "faiss",
          "parameters": {
            "ef_construction": 128,
            "m": 24
          }
        }
      }
    }
  }
}

{% include copy-curl.html %}

dimension 필드에는 선택한 임베딩 모델의 차원이 들어가야 해요.

2단계: ML 모델 등록 및 배포하기

시맨틱 하이라이팅에는 두 가지 종류의 모델이 필요해요:

  1. 텍스트 임베딩 모델: 검색 쿼리와 문서 텍스트를 벡터로 변환해요.
  2. 문장 하이라이팅 모델: 텍스트를 분석해 가장 관련성 높은 문장을 찾아내요.

먼저 텍스트 임베딩 모델을 등록하고 배포해요:

POST /_plugins/_ml/models/_register?deploy=true
{
  "name": "huggingface/sentence-transformers/all-MiniLM-L6-v2",
  "version": "1.0.2", 
  "model_format": "TORCH_SCRIPT"
}

{% include copy-curl.html %}

이 API는 배포 작업에 대한 task_id를 반환해요. Get ML Task API를 사용해 배포 상태를 확인해 보세요:

GET /_plugins/_ml/tasks/{your-task-id}

{% include copy-curl.html %}

state가 COMPLETED로 바뀌면 Get ML Task API가 배포된 모델의 모델 ID를 반환해요. 텍스트 임베딩 모델 ID를 잘 적어 두세요. 이후 단계에서 사용하게 돼요.

다음으로, 사전 학습된 시맨틱 문장 하이라이팅 모델을 등록해요:

POST /_plugins/_ml/models/_register?deploy=true
{
  "name": "amazon/sentence-highlighting/opensearch-semantic-highlighter-v1",
  "version": "1.0.0",
  "model_format": "TORCH_SCRIPT",
  "function_name": "QUESTION_ANSWERING"
}

{% include copy-curl.html %}

Get ML Task API를 사용해 배포 상태를 확인해 주세요. 시맨틱 하이라이팅 모델 ID도 잘 적어 두세요. 이후 단계에서 사용하게 돼요.

프로덕션 환경에서는 로컬에 배포한 모델 대신 외부 호스팅 모델을 사용하는 것을 고려해 보세요. 외부 호스팅 모델은 확장성과 리소스 격리가 더 뛰어나고, 배치 추론(batch inference) 같은 고급 기능도 지원해요. 외부 호스팅 모델 배포에 대한 내용은 외부 호스팅 모델 연결하기를 참고하세요. {: .tip}

3단계(선택 사항): ingest pipeline 설정하기

인덱싱 중에 임베딩을 자동으로 생성하려면 ingest pipeline을 만들어 주세요:

PUT /_ingest/pipeline/nlp-ingest-pipeline
{
  "description": "A pipeline to generate text embeddings",
  "processors": [
    {
      "text_embedding": {
        "model_id": "your-text-embedding-model-id",
        "field_map": {
          "text": "text_embedding"
        }
      }
    }
  ]
}

{% include copy-curl.html %}

이 파이프라인을 인덱스의 기본 파이프라인으로 설정해요:

PUT /neural-search-index/_settings
{
  "index.default_pipeline": "nlp-ingest-pipeline"
}

{% include copy-curl.html %}

4단계: 데이터 인덱싱하기

이제 샘플 문서를 몇 개 인덱싱해 봐요. ingest pipeline을 설정했다면 임베딩이 자동으로 생성돼요:

POST /neural-search-index/_doc/1
{
  "text": "Alzheimer's disease is a progressive neurodegenerative disorder characterized by accumulation of amyloid-beta plaques and neurofibrillary tangles in the brain. Early symptoms include short-term memory impairment, followed by language difficulties, disorientation, and behavioral changes. While traditional treatments such as cholinesterase inhibitors and memantine provide modest symptomatic relief, they do not alter disease progression. Recent clinical trials investigating monoclonal antibodies targeting amyloid-beta, including aducanumab, lecanemab, and donanemab, have shown promise in reducing plaque burden and slowing cognitive decline. Early diagnosis using biomarkers such as cerebrospinal fluid analysis and PET imaging may facilitate timely intervention and improved outcomes."
}

{% include copy-curl.html %}

POST /neural-search-index/_doc/2
{
  "text": "Major depressive disorder is characterized by persistent feelings of sadness, anhedonia, and neurovegetative symptoms affecting sleep, appetite, and energy levels. First-line pharmacological treatments include selective serotonin reuptake inhibitors (SSRIs) and serotonin-norepinephrine reuptake inhibitors (SNRIs), with response rates of approximately 60-70%. Cognitive-behavioral therapy demonstrates comparable efficacy to medication for mild to moderate depression and may provide more durable benefits. Treatment-resistant depression may respond to augmentation strategies including atypical antipsychotics, lithium, or thyroid hormone. Electroconvulsive therapy remains the most effective intervention for severe or treatment-resistant depression, while newer modalities such as transcranial magnetic stimulation and ketamine infusion offer promising alternatives with fewer side effects."
}

{% include copy-curl.html %}

POST /neural-search-index/_doc/3
{
   "text" : "Cardiovascular disease remains the leading cause of mortality worldwide, accounting for approximately one-third of all deaths. Risk factors include hypertension, diabetes mellitus, smoking, obesity, and family history. Recent advancements in preventive cardiology emphasize lifestyle modifications such as Mediterranean diet, regular exercise, and stress reduction techniques. Pharmacological interventions including statins, beta-blockers, and ACE inhibitors have significantly reduced mortality rates. Emerging treatments focus on inflammation modulation and precision medicine approaches targeting specific genetic profiles associated with cardiac pathologies."
}

{% include copy-curl.html %}

5단계: 시맨틱 하이라이팅 수행하기

neural search 쿼리에 시맨틱 하이라이터를 결합해요:

  1. neural 쿼리를 사용해 텍스트 임베딩 모델로 쿼리 텍스트와 의미적으로 유사한 문서를 찾아요.
  2. highlight 섹션을 추가해요.
  3. highlight.fields에 text 필드(또는 하이라이팅하려는 콘텐츠가 담긴 다른 필드)를 지정해요.
  4. 이 필드의 type을 semantic으로 설정해요.
  5. 전역 highlight.options 객체를 추가해요.
  6. options에 배포한 문장 하이라이팅 모델의 model_id를 넣어 주세요.

다음 요청을 사용해 상위 다섯 개의 일치 문서(k 파라미터로 지정)를 가져와 보세요. 플레이스홀더 모델 ID(TEXT_EMBEDDING_MODEL_ID와 SEMANTIC_HIGHLIGHTING_MODEL_ID)는 2단계에서 배포가 성공한 후 얻은 모델 ID로 바꿔 주세요:

POST /neural-search-index/_search
{
  "_source": {
    "excludes": ["text_embedding"] // Exclude the large embedding from the source
  },
  "query": {
    "neural": {
      "text_embedding": {
        "query_text": "treatments for neurodegenerative diseases",
        "model_id": "<your-text-embedding-model-id>", 
        "k": 2
      }
    }
  },
  "highlight": {
    "fields": {
      "text": {
        "type": "semantic"
      }
    },
    "options": {
      "model_id": "<your-semantic-highlighting-model-id>" 
    }
  }
}

{% include copy-curl.html %}

검색 결과의 각 항목에는 highlight 객체가 포함돼요. highlight 객체의 지정된 text 필드에는 원본 텍스트가 담기며, 의미적으로 가장 관련성이 높은 문장은 기본적으로 <em> 태그로 감싸져요:

{
  "took": 711,
  "timed_out": false,
  "_shards": {
    "total": 1,
    "successful": 1,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": {
      "value": 2,
      "relation": "eq"
    },
    "max_score": 0.52716815,
    "hits": [
      {
        "_index": "neural-search-index",
        "_id": "1",
        "_score": 0.52716815,
        "_source": {
          "text": "Alzheimer's disease is a progressive neurodegenerative disorder ..." // Shortened for brevity
        },
        "highlight": {
          "text": [
            // Highlighted sentence may differ based on the exact model used
            "Alzheimer's disease is a progressive neurodegenerative disorder characterized by accumulation of amyloid-beta plaques and neurofibrillary tangles in the brain. Early symptoms include short-term memory impairment, followed by language difficulties, disorientation, and behavioral changes. While traditional treatments such as cholinesterase inhibitors and memantine provide modest symptomatic relief, they do not alter disease progression. <em>Recent clinical trials investigating monoclonal antibodies targeting amyloid-beta, including aducanumab, lecanemab, and donanemab, have shown promise in reducing plaque burden and slowing cognitive decline.</em> Early diagnosis using biomarkers such as cerebrospinal fluid analysis and PET imaging may facilitate timely intervention and improved outcomes."
          ]
        }
      },
      {
        "_index": "neural-search-index",
        "_id": "2",
        "_score": 0.4364841,
        "_source": {
          "text": "Major depressive disorder is characterized by persistent feelings of sadness ..." // Shortened for brevity
        },
        "highlight": {
          "text": [
             // Highlighted sentence for document 2
            "Major depressive disorder is characterized by persistent feelings of sadness, anhedonia, and neurovegetative symptoms affecting sleep, appetite, and energy levels. First-line pharmacological treatments include selective serotonin reuptake inhibitors (SSRIs) and serotonin-norepinephrine reuptake inhibitors (SNRIs), with response rates of approximately 60-70%. <em>Cognitive-behavioral therapy demonstrates comparable efficacy to medication for mild to moderate depression and may provide more durable benefits.</em> Treatment-resistant depression may respond to augmentation strategies including atypical antipsychotics, lithium, or thyroid hormone. Electroconvulsive therapy remains the most effective intervention for severe or treatment-resistant depression, while newer modalities such as transcranial magnetic stimulation and ketamine infusion offer promising alternatives with fewer side effects."          ]
        }
      }
    ]
  }
}

semantic 하이라이터는 검색해 온 각 문서의 맥락 안에서, 쿼리("treatments for neurodegenerative diseases")와 의미적으로 관련 있다고 모델이 판단한 문장을 찾아내요. 필요하다면 pre_tags와 post_tags 파라미터를 사용해 하이라이트 태그를 커스터마이즈할 수 있어요. 자세한 내용은 하이라이팅 태그 변경하기를 참고하세요.

하이라이팅에 batch inference mode 사용하기

프로덕션 환경에서 여러 문서를 하이라이팅할 때 성능을 높이려면 batch inference mode를 활성화하는 것을 고려해 보세요. 이 모드는 문서마다 한 번씩 호출하는 대신, 모든 문서를 ML 추론 호출 한 번으로 처리해요. 자세한 내용은 Batch inference mode를 참고하세요.

다음 단계

시맨틱 하이라이팅 옵션과 설정에 대해 더 알고 싶다면 시맨틱 하이라이터 사용하기를 참고하세요.

더 알아보기 (Learn more)