본문 바로가기
반응형
Data/Elasticsearch

Python(파이썬)으로 Elasticsearch Index 생성하기

by JAMINS 2023. 4. 16.

index body로 인덱스 생성

from elasticsearch import Elasticsearch

es = Elasticsearch()

index_name = "my_index"

index_body = {
    "settings": {
        "number_of_shards": 1,
        "number_of_replicas": 0
    },
    "mappings": {
        "properties": {
            "title": {"type": "text"},
            "content": {"type": "text"}
        }
    }
}

response = es.indices.create(index=index_name, body=index_body)
print(response)

위 코드에서 index_name 변수에 새로운 인덱스의 이름을 지정하고, index_body 변수에 인덱스의 설정 및 매핑 정보를 작성합니다. es.indices.create 함수를 호출하여 인덱스를 생성하고, 생성 결과를 확인할 수 있습니다.

이미 정의된 매핑 파일로 인덱스 생성

def test_create_es_index():
    host = "http://hostdomain" // es host 주소
    user = "test_user"    // user 명
    password = "password1"    // password

    es = Elasticsearch(host,
                       http_auth=(user, password),
                       headers={'Content-Type': 'application/json; charset=utf-8'},
                       timeout=30, max_retries=1)

    es_index = 'index1'
    mapping_file: str = './config/es_mapping.json'
    with open(mapping_file, 'r') as fp:
        mapping = json.load(fp)

    if es.indices.exists(index=es_index):
        es.indices.delete(index=es_index, ignore=400)
    es.indices.create(index=es_index, body=mapping, ignore=400)

'Data > Elasticsearch' 카테고리의 다른 글

Elasticsearch MacOS 로컬 설치 및 환경설정 방법  (0) 2023.04.17

댓글