[python] elasticsearch로 색인하기

HI·2024년 8월 21일

1. 색인 하기 (기본)

insert 색인

def es_idx():
	es = Elasticsearch("http://localhost:9200", timeout=60)
    doc = {
        'DATE':20240820
    }
 res = es.index(index='my_index', id=123, body=doc) 

update 색인 하기

def es_updateidx():
    ##ES
    es = Elasticsearch("http://localhost:9200")
    doc = {
        'doc':{'DATE':20240821}
    }
    res = es.update(index="my_index", id=123, body=doc)   #8부터는 body->doc??
    print(res['result'])

2. bulk로 색인 하기

insert 색인 하기

def bulk_idxing(index_name):
    es = Elasticsearch("http://localhost:9200")
    actions = []

    action = {
            '_op_type': 'index',
            '_index': index_name,
            '_id': 123,
            '_source': '{"num":123,"text":"hello"}'
    }

    print(action)
    actions.append(action)
    helpers.bulk(es, actions)    #bulk API 색인

update 색인 하기

def bulk_update(actions):
    ##ES
    es = Elasticsearch("http://localhost:9200")
    actions = []
    action = {
    	'_op_type': 'update', 
        '_index': 'my-index', 
        '_id': 5102029001568, 
        'doc': {'DATE': '9999'}
       }
    actions.append(action)
    success, failed =helpers.bulk(es, actions)

helpers.bulk를 사용하면 대량의 문서를 한번에 색인 할 수 있다.
actions 리스트에 actions을 append하여 대량의 색인 json 데이터 세트를 만들고 이를 색인한다.

[참고]
https://www.elastic.co/guide/en/elasticsearch/client/python-api/current/examples.html#ex-index
https://www.elastic.co/guide/en/elasticsearch/client/python-api/current/client-helpers.html

0개의 댓글