수색…


매개 변수

매개 변수 세부
호스트 hostport 포함 된 객체 형식의 호스트 배열입니다. 기본 host 는 'localhost'이고 port 는 9200입니다. 샘플 항목은 [{"host": "ip of es server", "port": 9200}] 와 유사 [{"host": "ip of es server", "port": 9200}]
sniff_on_start 클라이언트가 시작시 노드를 스니핑하도록하려면 부울 검색은 elasticsearch 클러스터의 노드 목록을 가져 오는 것을 의미합니다.
sniff_on_connection_fail 클라이언트가 활성화되어있을 때 연결이 실패 할 경우 스니핑을 트리거하는 부울입니다.
스니퍼 타임 아웃 각 스니핑 사이의 시간 차이 (초)
sniff_timeout 스니핑에 대한 단일 요청 시간 (초)
retry_on_timeout 클라이언트가 다른 elasticsearch 노드에 접촉하는 시간 초과가 발생하거나 오류가 발생하는 경우 Booelan
http_auth 여기에 기본 http 인증을 username:password 형식으로 제공 할 수 있습니다 username:password

문서 인덱싱 (즉, 샘플 추가)

다음을 통해 필요한 Python 라이브러리를 설치하십시오.

$ pip install elasticsearch

Elasticsearch에 연결하여 문서 (예 : 데이터 입력)를 만들고 Elasticsearch를 사용하여 문서의 "색인"을 만듭니다.

from datetime import datetime
from elasticsearch import Elasticsearch

# Connect to Elasticsearch using default options (localhost:9200)
es = Elasticsearch()

# Define a simple Dictionary object that we'll index to make a document in ES
doc = {
    'author': 'kimchy',
    'text': 'Elasticsearch: cool. bonsai cool.',
    'timestamp': datetime.now(),
}

# Write a document
res = es.index(index="test-index", doc_type='tweet', id=1, body=doc)
print(res['created'])

# Fetch the document
res = es.get(index="test-index", doc_type='tweet', id=1)
print(res['_source'])

# Refresh the specified index (or indices) to guarantee that the document
#  is searchable (avoid race conditions with near realtime search)
es.indices.refresh(index="test-index")

# Search for the document
res = es.search(index="test-index", body={"query": {"match_all": {}}})
print("Got %d Hits:" % res['hits']['total'])

# Show each "hit" or search response (max of 10 by default)
for hit in res['hits']['hits']:
    print("%(timestamp)s %(author)s: %(text)s" % hit["_source"])

클러스터 연결

es = Elasticsearch(hosts=hosts, sniff_on_start=True, sniff_on_connection_fail=True, sniffer_timeout=60, sniff_timeout=10, retry_on_timeout=True)

빈 인덱스 만들기 및 매핑 설정

이 예제에서는 매핑을 정의하여 빈 인덱스를 만듭니다 (우리는 인덱스가없는 문서를 만듭니다).

먼저 ElasticSearch 인스턴스를 만들고 우리가 선택한 매핑을 정의합니다. 다음으로 인덱스가 존재하는지 확인하고 그렇지 않은 경우 인덱스 이름과 매핑 본문이 들어있는 인덱스 및 body 매개 변수를 지정하여 index 만듭니다.

from elasticsearch import Elasticsearch

# create an ElasticSearch instance
es = Elasticsearch()
# name the index
index_name = "my_index"
# define the mapping
mapping = {
    "mappings": {
        "my_type": {
                "properties": {
                    "foo": {'type': 'text'},
                    "bar": {'type': 'keyword'}
                }
            }
        }
    }
    
# create an empty index with the defined mapping - no documents added
if not es.indices.exists(index_name):
    res = es.indices.create(
        index=index_name,
        body=mapping
    )
    # check the response of the request
    print(res)
    # check the result of the mapping on the index
    print(es.indices.get_mapping(index_name))

부분 업데이트 및 쿼리 별 업데이트

부분 업데이트 : 부분적인 문서 업데이트가 필요한 경우에 사용됩니다. 즉, 다음 예제에서 id가 doc_id 문서의 필드 name 은 'John'으로 업데이트됩니다. 입력란이 누락 된 경우 문서에 추가됩니다.

doc = {
    "doc": {
        "name": "John"
    }
}
es.update(index='index_name',
          doc_type='doc_name',
          id='doc_id',
          body=doc)

질의 별 업데이트 : 조건을 만족하는 문서를 업데이트해야하는 경우에 사용됩니다. 즉, 다음 예에서는 name 필드가 'John'과 일치하는 문서의 수명을 업데이트합니다.

q = {
  "script": {
    "inline": "ctx._source.age=23",
    "lang": "painless"
  },
  "query": {
    "match": {
        "name": "John"
    }
  }
}

es.update_by_query(body=q, 
                   doc_type='doc_name', 
                   index='index_name')


Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow