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

Min hash token filter

원문 보기 위키 갱신

출처: 문서

본문

Min hash 토큰 필터

min_hash 토큰 필터는 MinHash 근사 알고리즘을 기반으로 토큰에 대한 해시를 생성하는 데 사용돼요. 이는 문서 간 유사성을 감지하는 데 유용해요. min_hash 토큰 필터는 (일반적으로 분석된 필드에서) 토큰 집합에 대한 해시를 생성해요.

파라미터

min_hash 토큰 필터는 다음 파라미터로 구성할 수 있어요.

파라미터 필수/선택 데이터 타입 설명
hash_count 선택 Integer 각 토큰에 대해 생성할 해시 값의 수예요. 이 값을 늘리면 일반적으로 유사성 추정의 정확도가 향상되지만 계산 비용이 증가해요. 기본값은 1이에요.
bucket_count 선택 Integer 사용할 해시 버킷의 수예요. 이 값은 해싱의 세분성에 영향을 줘요. 버킷 수가 많을수록 더 세밀한 세분성을 제공하고 해시 충돌을 줄이지만 더 많은 메모리가 필요해요. 기본값은 512예요.
hash_set_size 선택 Integer 각 버킷에 유지할 해시의 수예요. 이 값은 해싱 품질에 영향을 줄 수 있어요. 세트 크기가 클수록 유사성 감지가 더 좋아질 수 있지만 더 많은 메모리를 소비해요. 기본값은 1이에요.
with_rotation 선택 Boolean true로 설정하면 필터는 hash_set_size가 1인 경우, 빈 버킷을 순환 오른쪽에서 찾은 첫 번째 비어 있지 않은 버킷의 값으로 채워요. bucket_count 인수가 1을 초과하면 이 설정은 자동으로 true가 되고, 그렇지 않으면 false가 돼요.

예제

다음 예제 요청은 minhash_index라는 새 인덱스를 생성하고 min_hash 필터로 분석기를 구성해요.

PUT /minhash_index
{
  "settings": {
    "analysis": {
      "filter": {
        "minhash_filter": {
          "type": "min_hash",
          "hash_count": 3,
          "bucket_count": 512,
          "hash_set_size": 1,
          "with_rotation": false
        }
      },
      "analyzer": {
        "minhash_analyzer": {
          "type": "custom",
          "tokenizer": "standard",
          "filter": [
            "minhash_filter"
          ]
        }
      }
    }
  }
}

{% include copy-curl.html %}

생성된 토큰

다음 요청을 사용하여 분석기로 생성된 토큰을 확인해요.

POST /minhash_index/_analyze
{
  "analyzer": "minhash_analyzer",
  "text": "OpenSearch is very powerful."
}

{% include copy-curl.html %}

응답에는 생성된 토큰이 포함돼요 (토큰은 해시를 나타내므로 사람이 읽을 수 없어요).

{
  "tokens" : [
    {
      "token" : "\u0000\u0000㳠锯ੲ걌䐩䉵",
      "start_offset" : 0,
      "end_offset" : 27,
      "type" : "MIN_HASH",
      "position" : 0
    },
    {
      "token" : "\u0000\u0000㳠锯ੲ걌䐩䉵",
      "start_offset" : 0,
      "end_offset" : 27,
      "type" : "MIN_HASH",
      "position" : 0
    },
    ...

min_hash 토큰 필터의 유용성을 보여주기 위해, 다음 Python 스크립트를 사용하여 이전에 생성된 분석기로 두 문자열을 비교할 수 있어요.

from opensearchpy import OpenSearch
from requests.auth import HTTPBasicAuth

# Initialize the OpenSearch client with authentication
host = 'https://localhost:9200'  # Update if using a different host/port
auth = ('admin', 'admin')  # Username and password

# Create the OpenSearch client with SSL verification turned off
client = OpenSearch(
    hosts=[host],
    http_auth=auth,
    use_ssl=True,
    verify_certs=False,  # Disable SSL certificate validation
    ssl_show_warn=False  # Suppress SSL warnings in the output
)

# Analyzes text and returns the minhash tokens
def analyze_text(index, text):
    response = client.indices.analyze(
        index=index,
        body={
            "analyzer": "minhash_analyzer",
            "text": text
        }
    )
    return [token['token'] for token in response['tokens']]

# Analyze two similar texts
tokens_1 = analyze_text('minhash_index', 'OpenSearch is a powerful search engine.')
tokens_2 = analyze_text('minhash_index', 'OpenSearch is a very powerful search engine.')

# Calculate Jaccard similarity
set_1 = set(tokens_1)
set_2 = set(tokens_2)
shared_tokens = set_1.intersection(set_2)
jaccard_similarity = len(shared_tokens) / len(set_1.union(set_2))

print(f"Jaccard Similarity: {jaccard_similarity}")

응답에는 Jaccard 유사도 점수가 포함되어야 해요.

Jaccard Similarity: 0.8571428571428571

더 알아보기 (Learn more)