ID

Each document in OpenSearch has a unique _id field. This field is indexed, allowing you to retrieve documents using the GET API or the ids query.

If you do not provide an _id value, then OpenSearch automatically generates one for the document.

The following example request creates an index named test-index1 and adds two documents with different _id values:

  1. PUT test-index1/_doc/1
  2. {
  3. "text": "Document with ID 1"
  4. }
  5. PUT test-index1/_doc/2?refresh=true
  6. {
  7. "text": "Document with ID 2"
  8. }

copy

You can then query the documents using the _id field, as shown in the following example request:

  1. GET test-index1/_search
  2. {
  3. "query": {
  4. "terms": {
  5. "_id": ["1", "2"]
  6. }
  7. }
  8. }

copy

The response returns both documents with _id values of 1 and 2:

  1. {
  2. "took": 10,
  3. "timed_out": false,
  4. "_shards": {
  5. "total": 1,
  6. "successful": 1,
  7. "skipped": 0,
  8. "failed": 0
  9. },
  10. "hits": {
  11. "total": {
  12. "value": 2,
  13. "relation": "eq"
  14. },
  15. "max_score": 1,
  16. "hits": [
  17. {
  18. "_index": "test-index1",
  19. "_id": "1",
  20. "_score": 1,
  21. "_source": {
  22. "text": "Document with ID 1"
  23. }
  24. },
  25. {
  26. "_index": "test-index1",
  27. "_id": "2",
  28. "_score": 1,
  29. "_source": {
  30. "text": "Document with ID 2"
  31. }
  32. }
  33. ]
  34. }

copy

Limitations of the _id field

While the _id field can be used in various queries, it is restricted from use in aggregations, sorting, and scripting. If you need to sort or aggregate on the _id field, it is recommended to duplicate the _id content into another field with doc_values enabled. Refer to IDs query for an example.