elasticsearch의 문서를 동시에 업데이트하면 오류가 날까?

jinwook han·2022년 1월 4일
0

elasticsearch의 문서를 동시에 script를 통한 업데이트를 하면 오류가 날까?
-> 오류가 난다.

실험

하나의 문서에 대해 동시에 여러 개의 쿼리를 실행될 수 있도록 es 문서와 스크립트를 만들어보자.

1. 문서를 1개 생성한다.

문서에는 helloCount, byeCount 숫자 필드를 만들어서 0으로 설정한다.

2. 스크립트를 2개 준비한다.

helloCount.sh은 helloCount를 1씩 더하는 script 쿼리를 2000번 실행하는 스크립트다.
byeCount.sh는 같은 문서의 byeCount를 1씩 더하는 script 쿼리를 2000번 실행하는 스크립트다.

helloCount.sh:

SET=$(seq 1 2000)

for i in $SET
do
    curl -X POST --location "http://localhost:9299/test-1/_update/1" \
        -H "Content-Type: application/json" \
        -d "{
              \"script\" : {
                \"source\": \"ctx._source.helloCount += 1\",
                \"lang\": \"painless\"
                }
            }"
    # some instructions
done

byeCount.sh:

SET=$(seq 1 2000)

for i in $SET
do

    echo "Running loop seq "$i
    curl -X POST --location "http://localhost:9299/test-1/_update/1" \
        -H "Content-Type: application/json" \
        -d "{
              \"script\" : {
                \"source\": \"ctx._source.byeCount += 1\",
                \"lang\": \"painless\"
                }
            }"
    # some instructions
done

3. 스크립트 2개를 동시에 실행한다.

두 개의 스크립트를 동시에 실행하여, 동시에 업데이트 요청이 날아가는 상황을 재연할 것이다.
터미널을 두 개 띄워서 각 터미널별로 스크립트를 실행하자.

터미널 1: sh helloCount.sh
터미널 2: sh byeCount.sh

결과

helloCount.sh에서 실행한 2000개의 업데이트 쿼리 중 300~350개 정도가 에러가 났다.
마찬가지로 byeCount.sh에서 실행한 업데이트 쿼리들에서도 300~350개 정도가 에러가 났다.

에러 로그 ↓

[{"type":"version_conflict_engine_exception","reason":"[1]: version conflict, required seqNo [5222], primary term [1]. current document has seqNo [5223] and primary term [1]","index_uuid":"3q0fef-fQd6iwPdMtuOJ1A","shard":"4","index":"test-1"}],"type":"version_conflict_engine_exception","reason":"[1]: version conflict, required seqNo [5222], primary term [1]. current document has seqNo [5223] and primary term [1]","index_uuid":"3q0fef-fQd6iwPdMtuOJ1A","shard":"4","index":"test-1"},"status":409}

참고문서

https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-update-by-query.html

** 문서를 보니 seq_no로 낙관적 락을 구현하는 것 같다.
(일단 업데이트 한 뒤 -> 읽은 데이터가 달라졌다면 롤백)
https://www.elastic.co/guide/en/elasticsearch/reference/current/optimistic-concurrency-control.html

0개의 댓글