2013-08-28 19:24:34 -04:00
|
|
|
[[mapping-index-field]]
|
2015-07-19 19:24:29 -04:00
|
|
|
=== `_index` field
|
2013-08-28 19:24:34 -04:00
|
|
|
|
2015-11-30 02:42:56 -05:00
|
|
|
When performing queries across multiple indexes, it is sometimes desirable to
|
|
|
|
add query clauses that are associated with documents of only certain indexes.
|
|
|
|
The `_index` field allows matching on the index a document was indexed into.
|
|
|
|
Its value is accessible in `term`, or `terms` queries, aggregations,
|
|
|
|
scripts, and when sorting:
|
|
|
|
|
|
|
|
NOTE: The `_index` is exposed as a virtual field -- it is not added to the
|
|
|
|
Lucene index as a real field. This means that you can use the `_index` field
|
|
|
|
in a `term` or `terms` query (or any query that is rewritten to a `term`
|
|
|
|
query, such as the `match`, `query_string` or `simple_query_string` query),
|
|
|
|
but it does not support `prefix`, `wildcard`, `regexp`, or `fuzzy` queries.
|
2013-08-28 19:24:34 -04:00
|
|
|
|
2019-09-06 11:31:13 -04:00
|
|
|
[source,console]
|
2015-07-19 19:24:29 -04:00
|
|
|
--------------------------
|
|
|
|
# Example documents
|
2017-12-14 11:47:53 -05:00
|
|
|
PUT index_1/_doc/1
|
2015-07-19 19:24:29 -04:00
|
|
|
{
|
|
|
|
"text": "Document in index 1"
|
|
|
|
}
|
|
|
|
|
2017-12-14 11:47:53 -05:00
|
|
|
PUT index_2/_doc/2?refresh=true
|
2013-08-28 19:24:34 -04:00
|
|
|
{
|
2015-07-19 19:24:29 -04:00
|
|
|
"text": "Document in index 2"
|
|
|
|
}
|
|
|
|
|
|
|
|
GET index_1,index_2/_search
|
|
|
|
{
|
|
|
|
"query": {
|
|
|
|
"terms": {
|
|
|
|
"_index": ["index_1", "index_2"] <1>
|
|
|
|
}
|
|
|
|
},
|
|
|
|
"aggs": {
|
|
|
|
"indices": {
|
|
|
|
"terms": {
|
|
|
|
"field": "_index", <2>
|
|
|
|
"size": 10
|
|
|
|
}
|
|
|
|
}
|
|
|
|
},
|
|
|
|
"sort": [
|
|
|
|
{
|
|
|
|
"_index": { <3>
|
|
|
|
"order": "asc"
|
|
|
|
}
|
2013-08-28 19:24:34 -04:00
|
|
|
}
|
2015-07-19 19:24:29 -04:00
|
|
|
],
|
|
|
|
"script_fields": {
|
|
|
|
"index_name": {
|
2016-06-27 09:55:16 -04:00
|
|
|
"script": {
|
|
|
|
"lang": "painless",
|
2017-06-09 11:29:25 -04:00
|
|
|
"source": "doc['_index']" <4>
|
2016-06-27 09:55:16 -04:00
|
|
|
}
|
2015-07-19 19:24:29 -04:00
|
|
|
}
|
|
|
|
}
|
2013-08-28 19:24:34 -04:00
|
|
|
}
|
2015-07-19 19:24:29 -04:00
|
|
|
--------------------------
|
|
|
|
|
|
|
|
<1> Querying on the `_index` field
|
|
|
|
<2> Aggregating on the `_index` field
|
|
|
|
<3> Sorting on the `_index` field
|
2016-06-27 09:55:16 -04:00
|
|
|
<4> Accessing the `_index` field in scripts
|