index-field.asciidoc 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. [[mapping-index-field]]
  2. === `_index` field
  3. When performing queries across multiple indexes, it is sometimes desirable to
  4. add query clauses that are associated with documents of only certain indexes.
  5. The `_index` field allows matching on the index a document was indexed into.
  6. Its value is accessible in certain queries and aggregations, and when sorting
  7. or scripting:
  8. [source,console]
  9. --------------------------
  10. PUT index_1/_doc/1
  11. {
  12. "text": "Document in index 1"
  13. }
  14. PUT index_2/_doc/2?refresh=true
  15. {
  16. "text": "Document in index 2"
  17. }
  18. GET index_1,index_2/_search
  19. {
  20. "query": {
  21. "terms": {
  22. "_index": ["index_1", "index_2"] <1>
  23. }
  24. },
  25. "aggs": {
  26. "indices": {
  27. "terms": {
  28. "field": "_index", <2>
  29. "size": 10
  30. }
  31. }
  32. },
  33. "sort": [
  34. {
  35. "_index": { <3>
  36. "order": "asc"
  37. }
  38. }
  39. ],
  40. "script_fields": {
  41. "index_name": {
  42. "script": {
  43. "lang": "painless",
  44. "source": "doc['_index']" <4>
  45. }
  46. }
  47. }
  48. }
  49. --------------------------
  50. <1> Querying on the `_index` field
  51. <2> Aggregating on the `_index` field
  52. <3> Sorting on the `_index` field
  53. <4> Accessing the `_index` field in scripts
  54. The `_index` field is exposed virtually -- it is not added to the Lucene index
  55. as a real field. This means that you can use the `_index` field in a `term` or
  56. `terms` query (or any query that is rewritten to a `term` query, such as the
  57. `match`, `query_string` or `simple_query_string` query), as well as `prefix`
  58. and `wildcard` queries. However, it does not support `regexp` and `fuzzy`
  59. queries.
  60. Queries on the `_index` field accept index aliases in addition to concrete
  61. index names.
  62. NOTE: When specifying a remote index name such as `cluster_1:index_3`, the
  63. query must contain the separator character `:`. For example, a `wildcard` query
  64. on `cluster_*:index_3` would match documents from the remote index. However, a
  65. query on `cluster*index_1` is only matched against local indices, since no
  66. separator is present. This behavior aligns with the usual resolution rules for
  67. remote index names.