본문 바로가기
개발일기/파이썬

[python/elasitcsearch] 파이썬 elasticsearch(일래스틱서치) 라이브러리 사용하기

by 프로그래머콩 2019. 1. 9.


# python elasticsearch 설치

- 설치 및 사용 요약

1. pip로 elasticsearch 설치

- 터미널 창에 다음 명령어를 입력후 실행하면, 간단하게 설치 완료됨. 

[$ pip install elasticsearch ]
또는
[$ pip3 install elasticsearch ]



2. import


import elasticsearch
from elasticsearch import helpers





3. 사용 준비 및 확인

es_client = elasticsearch.Elasticsearch(“localhost:9200”) 
print (es_client.info())


4. insert

es_client.index(index='test_index', doc_type=folder,  body=r)

“”"
###
index = db이름
doc_type = type 이름
body = 내용 
###
“”"





뭘 해볼거냐면
특정 폴더 내에 있는 .csv 파일을 순차적으로 읽고
elasticsearch에 저장하는? 그런 작업 해볼까 함


# 개요

- python 동작순서는 아래와 같음

1. “./data/“아래 있는 폴더를 순차적으로 읽기

2. 각 폴더 아래 csv파일이 저장되어있가 가정하고, 파일 목록 불러오기

3. 각 파일 읽고 elasticsearch에 저장





# csv파일 정규화 조건

type
구분

타입A

id

일자
“201803” 까지 읽기
(값 1)
스키마
조건 : ‘시군구’로 시작되고, length가 2이상이 된다면 
(값 2)
그 이후 차례대로 넣기


# elasticsearch에  최종 저장될 형태는 아래와 같음

Index Document_Type Id
(Data)

AA ----

- 타입A----------

 - 201802----
- (데이터)


 - 201803----
- (데이터)

- 타입B--------
- 201802----
- (데이터)


- 201803----
- (데이터)

- 타입C--------
- 201802----
- (데이터)


- 201803----
- (데이터)



# elasticsearch 6.x에서 발생한 문제는... 




다음과 같이 mapping을 생성했다고 가정했을 때,

index : get-together / Document_Type : new-events

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
curl -XPUT 'localhost:9200/get-together/_mapping/new-events?pretty' -d '{
    "new-events": {
       "properties": {
            "name": {
                "type": "string",
                "index": "analyzed"
            }, 
            "name2": {
                "type": "string",
                "index": "not_analyzed"
            },
            "name3": {
                "type": "string",
                "index": "no"
            }            
        }
    }
}'
cs


매핑이 생성되면 성공 메세지가 출력된다.

1
2
3
{
  "acknowledged" : true
}
cs


이와 같이 new-events type에 대한 매핑을 생성 후 새로운 속성을 추가해보자.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
curl -XPUT 'localhost:9200/get-together/_mapping/new-events?pretty' -d '{
    "new-events": {
       "properties": {
            "name": {
                "type": "string",
                "index": "analyzed"
            }, 
            "name2": {
                "type": "string",
                "index": "not_analyzed"
            },
            "name3": {
                "type": "string",
                "index": "no"
            },
            "name4": {
                "type": "string",
                "index": "no"
            }           
        }
    }
}'
cs


새로운 속성이 정의된 매핑을 적용 후 매핑을 조회해 보자. 새롭게 추가된 name4 속성이 출력됨을 알 수 있다.

1
curl -XGET localhost:9200/get-together/_mapping/new-events?pretty
cs


허나 한번 정해진 속성은 변경이 불가능하다. 또한 필드 색인하는 방식도 변경할 수 없다.

name4 속성을 integer로 변경하여 매핑을 수정해 보자.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
curl -XPUT 'localhost:9200/get-together/_mapping/new-events?pretty' -d '{
    "new-events": {
       "properties": {
            "name": {
                "type": "string",
                "index": "analyzed"
            }, 
            "name2": {
                "type": "string",
                "index": "not_analyzed"
            },
            "name3": {
                "type": "string",
                "index": "no"
            },
            "name4": {
                "type": "integer",
                "index": "no"
            }           
        }
    }
}'
cs


다음과 같은 오류가 발생됨을 알 수 있다.

1
2
3
4
5
6
7
8
9
10
11
{
    "error": {
        "root_cause": [{
            "type": "mapper_parsing_exception",
            "reason": "wrong value for index [integer] for field [name4]"
        }],
        "type": "mapper_parsing_exception",
        "reason": "wrong value for index [integer] for field [name4]"
    },
    "status": 400
}
cs



* 결론 : 하나의 인덱스에, 하나의 document_type만 설정 가능한 것을 알 수 있다
이것은 6.x 이상 버전의 특징인 것으로 밝혀졌다.

elasitcsearch 5.x 이하 버전에선 join과 비슷한 쿼리가 없고
document_type 가 중복이 가능하다.

6.x에서는 좀 더 많은 기능이 추가, 간소화 됐지만
document_type 중복을 불가 즉,
document_type이 구색 갖추기 밖데 되지않는 그런 느낌?




그렇다면


(datatype = 다세대매매, 아파트매매 등등 / datadate = 201803, 201802 등등 )
‘meamea-‘+data_type/_doc/data_data 형태로 저장함

찾을때는

이런 형태로 찾으면 됨


다이나믹 type혹은 여러개 type사용 하고 싶은 경우는 5.x버전 사용하기

비슷한 효과를 원한다면 join, reindex, template 을 이용하면 됨 그러나 다른 uri를 하나 더 거쳐야하는 번거로움이 있을 수 있음