본문 바로가기
infra/ELK

[ELK] Elasticsearch의 데이터 검색 - search API

by hjhello423 2020. 1. 19.

ES의 데이터 검색 방법에 대한 내용을 정리해 보았습니다.

 

데이터 검색 테스트를 하기 위해 ES에서 제공해주는 샘플 데이터를 이용해 보겠습니다.

링크에서 accounts.json 파일을 다운로드하고 ES에 insert 해보겠습니다.

 


bulk insert

대량에 데이터를 insert 할 때는 bulk insert를 이용해야 합니다. 정확히 얘기하자면 json 타입으로 정리된 파일의 데이터를 insert 해보도록 하겠습니다.

bulk insert를 이용하면 아래와 같이 insert 된 데이터들에 대한 정보가 출력됩니다.

curl -XPOST 'localhost:9200/bank/account/_bulk?pretty' --data-binary @accounts.json -H 'Content-Type:application/json'


{
      ...생략...
      
      "index" : {
        "_index" : "bank",
        "_type" : "account",
        "_id" : "990",
        "_version" : 1,
        "result" : "created",
        "_shards" : {
          "total" : 2,
          "successful" : 1,
          "failed" : 0
        },
        "_seq_no" : 998,
        "_primary_term" : 1,
        "status" : 201
      }
    },
    {
      "index" : {
        "_index" : "bank",
        "_type" : "account",
        "_id" : "995",
        "_version" : 1,
        "result" : "created",
        "_shards" : {
          "total" : 2,
          "successful" : 1,
          "failed" : 0
        },
        "_seq_no" : 999,
        "_primary_term" : 1,
        "status" : 201
      }
    }
  ]
}

bulk insert 후에 index를 조회하면 아래와 같이 bank index가 생성된 것을 확인할 수 있습니다.

docs.count를 보니 1000개의 데이터가 insert 된 것을 확인할 수 있습니다.

curl -XGET 'localhost:9200/_cat/indices?v'
health status index                    uuid                   pri rep docs.count docs.deleted store.size pri.store.size
yellow open   logstash                 961W116OTqeuihFKVsbfVw   1   1         51            0    122.5kb        122.5kb
yellow open   bank                     2nJbnAaJRfezVoCpjLhOgA   1   1       1000            0    414.2kb        414.2kb
green  open   .kibana_task_manager_1   3_qkg0zPQoKZ-Q_vT9HPDQ   1   0          2            0     32.6kb         32.6kb
green  open   .apm-agent-configuration KVDr8cy2Th6xm8y5nWH5Kw   1   0          0            0       283b           283b
green  open   .kibana_1                7NwZy05jTNCinTw3TxaTeA   1   0       1062           62    536.1kb        536.1kb

 


URI Search

이 내용에 관한 자세한 설명은 docs를 확인해보세요.

데이터를 조회할 때 아래의 형식으로 데이터 조회 쿼리를 사용합니다.

parameter에 들어가는 키워드들은 docs링크에 잘 정리되어 있습니다.

GET /<index>/_search?q=<parameter>

 

bulk insert를 통해 생성한 bank index의 특정 document를 조회해보도록 하겠습니다.

age값이 32인 document를 모두 출력해 보도록 하죠. (너무 길어서 중간에 생략했습니다.)

curl -XGET 'localhost:9200/bank/account/_search?q=age:32&pretty'
{
  "took" : 18,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 52,
      "relation" : "eq"
    },
    "max_score" : 1.0,
    "hits" : [
      {
        "_index" : "bank",
        "_type" : "account",
        "_id" : "1",
        "_score" : 1.0,
        "_source" : {
          "account_number" : 1,
          "balance" : 39225,
          "firstname" : "Amber",
          "lastname" : "Duke",
          "age" : 32,
          "gender" : "M",
          "address" : "880 Holmes Lane",
          "employer" : "Pyrami",
          "email" : "amberduke@pyrami.com",
          "city" : "Brogan",
          "state" : "IL"
        }
      },
      
      ...생략...
     
      {
        "_index" : "bank",
        "_type" : "account",
        "_id" : "950",
        "_score" : 1.0,
        "_source" : {
          "account_number" : 950,
          "balance" : 30916,
          "firstname" : "Sherrie",
          "lastname" : "Patel",
          "age" : 32,
          "gender" : "F",
          "address" : "658 Langham Street",
          "employer" : "Futurize",
          "email" : "sherriepatel@futurize.com",
          "city" : "Garfield",
          "state" : "OR"
        }
      }
    ]
  }

응답 json의 각 key가 의미하는 바는 링크에서 확인해보시길 바랍니다.

hits.total.value:52에서 조회 결과가 52개인 것을 알 수 있습니다.

 

  • took: ES가 request를 처리하는데 걸린 시간(ms)
  • timed_out: (boolean) true인 경우 request가 완료되기 전에 시간이 초과된 경우입니다. 결과값이 부분적이거나 비어있을 수 있습니다.
  • _shards: (Object) 요청에 사용된 샤드 수를 포함하는 객체입니다. 
    • total: (Integer) 할당되지 않은 샤드를 포함하여 쿼리가 필요한 총 샤드 수입니다.
    • successful: (Integer) request를 성공적으로 실행한 샤드의 수입니다.
    • skipped : (Integer) 경량 검사로 인해이 샤드에서 일치하는 문서가 없음을 인식하여 요청을 건너뛴 샤드 수입니다. 이는 일반적으로 검색 요청에 범위 필터가 포함되어 있고 샤드에 해당 범위를 벗어난 값만 있는 경우에 발생합니다.
    • failed: (Integer) 요청을 실행하지 못한 샤드 수입니다. 할당되지 않은 샤드는 성공 또는 실패로 간주되지 않습니다. 따라서 전체보다 작거나 실패한 것은 일부 샤드가 할당되지 않았음을 나타냅니다.
  • hits : (Object)  반환된 document 및 meta data를 포함합니다.
    • total: (Object) 반환 된 document 수에 대한 meta data입니다.
    • value: 반환된 documents의 총 수.
    • relation: Indicates whether the number of documents returned. Returned values are:

      • eq: Accurate
      • gte: Lower bound, including returned documents
  • max_score: (Float) Highest returned document _score. The _score parameter is a 32-bit floating point number used to determine the relevance of the returned document. This parameter value is null for requests that do not sort by _score.
  • hits: (Array of objects) Array of returned document objects.
    • _index: Name of the index containing the returned document.
    • _type: Document type.
    • _id: document의 고유 id 값. id는 return 된 index 내에서만 유효합니다.
    • _score: Positive 32-bit floating point number used to determine the relevance of the returned document.
    • _source: Object containing the original JSON body passed for the document at index time.

 


Request Body Search

request Body에 쿼리를 담아 search작업을 진행할 수도 있습니다.

아래의 요청은 위에서 진행한 request와 같은 의미를 나타 냅니다.

결과 또한 위에서 진행한 request와 동일합니다.

GET /bank/
{
	"query": {
		"term": {"age":32}
    }
}
curl -XGET 'localhost:9200/bank/_search?pretty' -d '{"query":{"term":{"age":32}}}' -H 'Content-Type:application/json'

 

 

 

 


 

참조

반응형

댓글