nafas
nafas

Reputation: 5423

How to retrieve all document with version n in elastic search

ElasticSearch comes with versioning https://www.elastic.co/blog/versioning

Maybe I misunderstood the meaning of the versioning here.

I want to find all the documents that are in version 1 so I can update them.

An obvious way is to go through all the document one by one and select those that are in version 1.

Question:

Is it possible to retrieve all the Documents that are in version 1 with ONE query?

Upvotes: 1

Views: 4091

Answers (2)

mgaert
mgaert

Reputation: 2388

You can use scripted _reindex into an empty temporary index. The target index will then contain just those documents that have _version=1.

You can add further query stanzas as well, to limit your raw input (using the reverse index, faster), as well as further painless conditions (per document, flexible), too.

# ES5, use "source" i/o "inline" for later ES versions.
http POST :9200/_reindex <<END
{
  "conflicts": "proceed",
  "source": {
    "index": "your-source-index"
  },
  "dest": {
    "index": "some-temp-index",
    "version_type": "external"
  },
  "script": {
    "lang": "painless",
    "inline": "if(ctx._version!=1){ctx.op='delete'}"
  }
}
END

Upvotes: 0

Cosmin Ababei
Cosmin Ababei

Reputation: 7072

Because of Elasticsearch distributed nature, it needs a way to ensure that changes are applied in the correct order. This is where _version comes into play. It's an internal way of making sure than an older version of a document never overwrites a newer version.

You can also use _version as a way to make sure that the document you want to delete / update hasn't been modified in the meantime - this is done by specifying the version number in the URL; for example PUT /website/blog/1?version=5 will succeed only if the current _version of the document stored in the index is 5.

You can read more about it here: Optimistic Concurrency Control

To answer your question,

Is it possible to retrieve all the Documents that are in version 1 with ONE query?

No.

Upvotes: 2

Related Questions