elasticsearch nested type 필드안에 배열 수정하기

개발새발·2022년 8월 6일
0

elasticsearch

목록 보기
33/54

ㅎㅅㅎ… 후 재밌다… 진짜 별의별거 다하는듯 ㅋㅋㅋ 이번에는 데이터 형태를 바꿔서 nested type 필드안에 배열을 넣어 이것저것 해봤다. 다 쓰면 너무 또 길어지니.. 간단히 보겠다.

데이터 구조 🤑

데이터 구조를 보자면 아래와 같다.

{
    "_index": "test",
    "_type": "_doc",
    "_id": "FgchZ4IB18RgfuY2w7UI",
    "_score": 3.302585,
    "_source": {
         "nestedtypefield": [ // nested type
            {
                "field1": "test", // keyword type
                "field2": [] //text type
             },
						{
               "field1": "test2", 
               "field2": [ 
									"test21",
                  "test22",
                  "test23"
								]
            }
          ]
    }
}

여기서 내가 하고 싶던 것! : 배열 형태의 field2 필드에 있는 element들을 어떻게 굴리고 싶었다. 🤽

다행히도 scriptnestedtypefieldfield2 , 바로 배열 형태 필드의 특정 데이터에 indexOf 를 사용하여 접근이 가능했다. 아래는 remove 함수를 사용하여 해당 데이터를 지우는 쿼리이다. 다른 함수를 이용해서도 해당 데이터에 접근하여 지우거나 수정하거나 등등이 가능하다. 이렇게 찾는데 오래걸렸다 ㅠㅠ

{
  "script": {
    "source": "def targets = ctx._source.nestedtypefields.findAll(nestedtypefield-> nestedtypefield.field1 == params.field1); for(target in targets) {target.field2.remove(target.field2.indexOf(params.field2))}",
    "lang": "painless",
    "params": {
      "field1": "test",
      "field2": "test_name"
    }
  },
  "query": {
    "bool": {
      "must": [
        {
          "nested": {
            "path": "nestedtypefields",
            "query": {
              "bool": {
                "must": [
                  {
                    "term": {
                      "nestedtypefields.field1": "test"
                    }
                  }
                ]
              }
            }
          }
        }
      ]
    }
  }
}
profile
발새발개

0개의 댓글