elasticsearch / / 2022. 12. 23. 06:57

elasticsearch nested 타입에 _update 사용법

post 인덱스 생성

PUT post
{
  "mappings": {
    "properties": {
      "id": {
        "type": "keyword"
      },
      "userId": {
        "type": "keyword"
      },
      "userName": {
        "type": "keyword"
      },
      "comments": {
        "type": "nested",
        "properties": {
          "commentId": {
            "type": "keyword"
          },
          "text": {
            "type": "text"
          }
        }
      }
    }
  }
}

id가 1인 데이터 입력

POST post/_doc/1
{
  "id": "1",
  "userId": "_",
  "userName": "_",
  "comments": []
}

comments에 데이터 입력

POST post/_update/1
{
  "script": {
    "source": "ctx._source.comments.add(params.comments)",
    "params": {
      "comments": {
        "commentId": "0",
        "text": "1..."
      }
    }
  }
}

add

POST post/_update/1
{
  "script": {
    "source": "ctx._source.comments.addAll(params.comments)",
    "params": {
      "comments": [
          {
            "commentId": "0",
            "text": "text 1"
          }
        ]
    }
  }
}

modify

POST post/_update/1
{
  "script": {
    "source": """
      for (int i=0; i<ctx._source.comments.size(); i++) {
        HashMap commentsMap = ctx._source.comments.get(i);
          if (commentsMap.commentId == params.comment.commentId) {
            ctx._source.comments[i] = params.comment;
          }
      }
      """,
    "params": {
      "comment": {
        "commentId": "0",
        "text": "updated"
      }
    }
  }
}

remove

GET post/_search
POST post/_update/1
{
  "script": {
    "source": "ctx._source.comments.removeIf(comment -> comment.commentId == params.commentId)",
    "params": {
      "commentId": "0"
    }
  }
}
반응형
  • 네이버 블로그 공유
  • 네이버 밴드 공유
  • 페이스북 공유
  • 카카오스토리 공유