Home > Software engineering >  How to implement Elasticsearch update_by_query that change the value of Boolean field using react bu
How to implement Elasticsearch update_by_query that change the value of Boolean field using react bu

Time:04-27

I'm trying to implement Elasticsearch update_by_query using react button onClick. When I click the react button it should set Elasticsearch document boolean field isCancelRun to true (index name is: run)

I would like to add the next query as a react function that will be executed with the button onClick:

curl -X POST "http://elasticsearch_ip_addr:9200/run-*/_update_by_query?pretty" -H "Content-Type: application/json" -d'
{
  "script": {
    "source": "ctx._source.isCancelRun = true;",
    "lang": "painless"
  },
  "query": {
    "term": {
      "runId": "20220419142721270"
    }
  }
}
'

I implemented the next function that should be called when the button is clicked:

export function cancelRunExecution(runIdToCancel) {
    fetch(`${ElasticSearch_BaseAddress}${"run-*"}/_update_by_query?pretty`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: 
            `{"query":{"bool":{"must":[{"match":{"runId":"${runIdToCancel}"}}]}}},
            script: {
                source: "ctx._source.isCancelRun = true;",
                lang: "painless"
            }`
        })
    .then(response => {
        if (!response.ok) { 
            return Promise.reject(response.statusText);
        }

        return response.json();
    });
}

ElasticSearch_BaseAddress = elasticsearch_ip_addr:9200/

The button implementation with onClick should execute cancelRunExecution function:

            <div>
                <button id="cancelRun" onClick={() => {
                    cancelRunExecution(props.run.runId);
                    var btn = document.getElementById("cancelRun");
                    btn.innerHTML = 'Run execution - canceled';                    
                }}>
                    Cancel Run Execution
                </button>
            </div>

The problem: It does not change the boolean field isCancelRun to true.

CodePudding user response:

What you send is not JSON since script, source and lang are not double-quoted.

Send this payload instead:

    body: 
        `{"query":{"bool":{"must":[{"match":{"runId":"${runIdToCancel}"}}]}}},
        "script": {
            "source": "ctx._source.isCancelRun = true;",
            "lang": "painless"
        }`
    })
  • Related