Python - Elastic Search Service [6.x] 생성, 조회, 삭제

2018. 10. 5. 15:01프로그래밍/Python & dJango

Elastic Search를 사용해 인덱스 생성 / Mapping / 조회 / 삭제 방법에 대해 알아보겠습니다.


* Enviroment

 - Python 3.6

 - Django 1.11

 - Auth : AWS4Auth

 - index : text_index

 - doc : _doc


* 이 포스트에서 편의를 위해 ElasticSearch Service를 "ES"로 부르도록 하겠습니다. 


1. ES 접속 

credentials = boto3.Session().get_credentials()
awsauth = AWS4Auth(credentials.access_key, credentials.secret_key, 'region', 'service')
es = Elasticsearch(hosts=[{'host': settings.ES_HOST, 'port': 443}],
           http_auth=awsauth,
            use_ssl=True,
            verify_certs=True,
            connection_class=RequestsHttpConnection)


2. 인덱스 생성을 위한 Document / Mapping 설정

document = {
	"mappings": {
	    "_doc": {
	        "properties": {
	            "type": {
	                "type": "keyword"
	            },
	            "id": {
	                "type": "integer"
	            },
	            "title": {
	                "type": "text",
	                "analyzer": "whitespace",
	            },
	            "contents": {
	                "type": "text"
	            },
	            "created_at": {
	                "type": "date"
	            }
            }
        }
    }
}	

 - Type을 정의한 이유는 데이터들의 출처를 구분하기 위함. (example: 게시글, 쇼핑, 등..)


3. 인덱스 생성

es.indices.create(index="test_index", body=document)


4. 데이터 인덱싱 

es.index(index="test_index", doc_type="_doc", body=body)


5. 데이터 조회


 - REST API

GET test_index/_doc/_search

GET index_name/doc_name/_search

아래의 쿼리는 title이 "검색어"이고, type이 "post"인 데이터를 조회하는 쿼리입니다. 

{
  "from": 0,
  "size": 5,
  "query": {
    "bool": {
      "must": [
        {
          "bool": {
            "should": [
              {
                "match": {
                  "title": "검색어"
                }
              }
            ]
          }
        }
      ],
      "filter": [
        {
          "term": {
            "type": "post"
          }
        }
      
      ]
    }
  },
  "sort": [
    "_score"
  ]
}

여러개의 필터를 사용할 경우 terms 사용


"terms": {
  "member_type": [
   "doctor",
     "all"
    ]
}

 - Python

es.search(index="test_index", doc_type="_doc", body=body)


데이터의 포맷은 아래와 같이 Json으로 응답이 옵니다.

{
  "took": 5,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": 7,
    "max_score": 2,
    "hits": [
      {
        "_index": "test_index",
        "_type": "_doc",
        "_id": "X14VQmYBDFDy57OpEriV",
        "_score": 2,
        "_source": {
          
        }
      }
    ]
  }
}

- took : 걸린시간

- timeout : 타임아웃 여부

- _shards : 샤딩관련 내용

- hits : 응답 데이터 정보 (* 검색결과 데이터는 hits > hits > _source 안에 데이터가 있습니다.)



6. 데이터 삭제

es.delete(index="test_index", doc_type="_doc", id="X14VQmYBDFDy57OpEriV"))



'프로그래밍 > Python & dJango' 카테고리의 다른 글

[Python] classmethod 와 staticmethod  (0) 2016.11.16
[django] 리스트 순번  (0) 2016.10.23
[Python] 집합 (set)  (0) 2016.10.19
[django] convert integer to string  (0) 2016.10.19
[dJango] Q expression  (0) 2016.10.19