Index

When querying across multiple indexes, you may need to filter results based on the index into which a document was indexed. The index field matches documents based on their index.

The following example request creates two indexes, products and customers, and adds a document to each index:

  1. PUT products/_doc/1
  2. {
  3. "name": "Widget X"
  4. }
  5. PUT customers/_doc/2
  6. {
  7. "name": "John Doe"
  8. }

copy

You can then query both indexes and filter the results using the _index field, as shown in the following example request:

  1. GET products,customers/_search
  2. {
  3. "query": {
  4. "terms": {
  5. "_index": ["products", "customers"]
  6. }
  7. },
  8. "aggs": {
  9. "index_groups": {
  10. "terms": {
  11. "field": "_index",
  12. "size": 10
  13. }
  14. }
  15. },
  16. "sort": [
  17. {
  18. "_index": {
  19. "order": "desc"
  20. }
  21. }
  22. ],
  23. "script_fields": {
  24. "index_name": {
  25. "script": {
  26. "lang": "painless",
  27. "source": "doc['_index'].value"
  28. }
  29. }
  30. }
  31. }

copy

In this example:

  • The query section uses a terms query to match documents from the products and customers indexes.
  • The aggs section performs a terms aggregation on the _index field, grouping the results by index.
  • The sort section sorts the results by the _index field in ascending order.
  • The script_fields section adds a new field called index_name to the search results containing the _index field value for each document.

Querying on the _index field

The _index field represents the index into which a document was indexed. You can use this field in your queries to filter, aggregate, sort, or retrieve index information for your search results.

Because the _index field is automatically added to every document, you can use it in your queries like any other field. For example, you can use the terms query to match documents from multiple indexes. The following example query returns all documents from the products and customers indexes:

  1. {
  2. "query": {
  3. "terms": {
  4. "_index": ["products", "customers"]
  5. }
  6. }
  7. }

copy