1

I'm trying to make a single query for updating the one field value in ES index.

I have a index pages which contain information about the pages (id, name, time, parent_page_id, child_count etc)

I can update the field parent_page_id with number of documents which have this page id as parent_page_id

I can update the field with default single value like:

PUT HOST_ADDRESS/pages/_update_by_query
{
  "script": {
    "source": "def child_count = 0; ctx._source.child_count = child_count;",
    "lang": "painless"
  },
  "query": {
    "match_all": {}
  }
}

I'm trying with this code to get child count but its not working.

"source": "def child_count = 0; client.prepareSearch('pages').setQuery(QueryBuilders.termQuery("parent_page_id", "ctx._source.id")).get().getTotal().getDocs().getCount(); ctx._source.child_count = child_count;",
    "lang": "painless"

My question is, how can i make a sub count-query in script to have a real child count in variable child_count

3
  • Are these child objects nested in the pages index? Commented Mar 25, 2021 at 13:35
  • no, the page index just every page as single object with parent page id Commented Mar 25, 2021 at 13:41
  • In that case, you'll need to join the data manually. It's not possible in ES to get data from an index and update another. So, you'll need to program that logic yourself. Joe's answer has a viable solution for this :) Commented Mar 25, 2021 at 14:08

1 Answer 1

2

Scripting doesn't work like this — you cannot use java DSL in there. There's no concept of client or QueryBuilders etc in the Painless contexts.

As such, you'll need to obtain the counts before you proceed to update the doc(s) with a script.

Tip: scripts are reusable when you store them:

POST HOST_ADDRESS/_scripts/update_child_count
{
  "script": {
    "lang": "painless",
    "source": "ctx._source.child_count = params.child_count"
  }
}

and then apply via the id:

PUT HOST_ADDRESS/pages/_update_by_query
{
  "script": {
    "id": "update_child_count",     <-- no need to write the Painless code again
    "params": {
      "child_count": 987
    }   
  },
  "query": {
    "term": {
      "parent_page_id": 123
    }
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @joe-sorocin for your answer.
You're welcome. If it helped, please upvote it. If it solved your issue, you can mark it as accepted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.