Elasticsearch

[Elasticsearch] Elastic-builder - 원하는 필드만 조회

Edyo 2023. 2. 27. 11:29

Elasticsearch 에서도 원하는 특정 필드만 조회 할 수 있다.

_source 필드를 이용하면 가능한데, Elastic-builder에서는 source() 인스턴스를 사용하면 된다.

 

Elastic-builder 공식문서 내용은 아래와 같다.

💡 source()

Allows to control how the _source field is returned with every hit. You can turn off _source retrieval by passing false. It also accepts one(string) or more wildcard(array) patterns to control what parts of the _source should be returned An object can also be used to specify the wildcard patterns for includes and excludes.
source(source: (boolean | string | Array | Object)): RequestBodySearch​

Parameters
source ((boolean | string | Array | Object))

Returns

RequestBodySearch: returns this so that calls can be chained

Example
// To disable `_source` retrieval set to `false`:
const reqBody = esb.requestBodySearch()
    .query(esb.termQuery('user', 'kimchy'))
    .source(false);
// The `_source` also accepts one or more wildcard patterns to control what
// parts of the `_source` should be returned:
const reqBody = esb.requestBodySearch()
    .query(esb.termQuery('user', 'kimchy'))
    .source('obj.*');

// OR
const reqBody = esb.requestBodySearch()
    .query(esb.termQuery('user', 'kimchy'))
    .source([ 'obj1.*', 'obj2.*' ]);
// The `_source` also accepts one or more wildcard patterns to control what
// parts of the `_source` should be returned:
const reqBody = esb.requestBodySearch()
    .query(esb.termQuery('user', 'kimchy'))
    .source('obj.*');

// OR
const reqBody = esb.requestBodySearch()
    .query(esb.termQuery('user', 'kimchy'))
    .source([ 'obj1.*', 'obj2.*' ]);

 

includes 에는 조회하고 싶은 필드 이름을 넣어주고,

excludes 에는 제외하고 싶은 필드 이름을 넣어준다.