Spec-Zone.ru › Elasticsearch 8
›Elasticsearch Руководство [8.17] ›Отображение ›Метаданные поля

Поле _index

При выполнении запросов по нескольким индексам иногда бывает желательно добавить запросы, связанные с документами только определенных индексов. Поле _index позволяет сопоставлять индекс, в который был индексирован документ. Его значение доступно в некоторых запросах и агрегациях, а также при сортировке или выполнении скриптов:

resp = client.index(
    index="index_1",
    id="1",
    document={
        "text": "Document in index 1"
    },
)
print(resp)

resp1 = client.index(
    index="index_2",
    id="2",
    refresh=True,
    document={
        "text": "Document in index 2"
    },
)
print(resp1)

resp2 = client.search(
    index="index_1,index_2",
    query={
        "terms": {
            "_index": [
                "index_1",
                "index_2"
            ]
        }
    },
    aggs={
        "indices": {
            "terms": {
                "field": "_index",
                "size": 10
            }
        }
    },
    sort=[
        {
            "_index": {
                "order": "asc"
            }
        }
    ],
    script_fields={
        "index_name": {
            "script": {
                "lang": "painless",
                "source": "doc['_index']"
            }
        }
    },
)
print(resp2)
response = client.index(
  index: 'index_1',
  id: 1,
  body: {
    text: 'Document in index 1'
  }
)
puts response

response = client.index(
  index: 'index_2',
  id: 2,
  refresh: true,
  body: {
    text: 'Document in index 2'
  }
)
puts response

response = client.search(
  index: 'index_1,index_2',
  body: {
    query: {
      terms: {
        _index: [
          'index_1',
          'index_2'
        ]
      }
    },
    aggregations: {
      indices: {
        terms: {
          field: '_index',
          size: 10
        }
      }
    },
    sort: [
      {
        _index: {
          order: 'asc'
        }
      }
    ],
    script_fields: {
      index_name: {
        script: {
          lang: 'painless',
          source: "doc['_index']"
        }
      }
    }
  }
)
puts response
const response = await client.index({
  index: "index_1",
  id: 1,
  document: {
    text: "Document in index 1",
  },
});
console.log(response);

const response1 = await client.index({
  index: "index_2",
  id: 2,
  refresh: "true",
  document: {
    text: "Document in index 2",
  },
});
console.log(response1);

const response2 = await client.search({
  index: "index_1,index_2",
  query: {
    terms: {
      _index: ["index_1", "index_2"],
    },
  },
  aggs: {
    indices: {
      terms: {
        field: "_index",
        size: 10,
      },
    },
  },
  sort: [
    {
      _index: {
        order: "asc",
      },
    },
  ],
  script_fields: {
    index_name: {
      script: {
        lang: "painless",
        source: "doc['_index']",
      },
    },
  },
});
console.log(response2);
PUT index_1/_doc/1
{
  "text": "Document in index 1"
}

PUT index_2/_doc/2?refresh=true
{
  "text": "Document in index 2"
}

GET index_1,index_2/_search
{
  "query": {
    "terms": {
      "_index": ["index_1", "index_2"] 
    }
  },
  "aggs": {
    "indices": {
      "terms": {
        "field": "_index", 
        "size": 10
      }
    }
  },
  "sort": [
    {
      "_index": { 
        "order": "asc"
      }
    }
  ],
  "script_fields": {
    "index_name": {
      "script": {
        "lang": "painless",
        "source": "doc['_index']" 
      }
    }
  }
}

Запрос на поле _index

Агрегирование по полю _index

Сортировка по полю _index

Доступ к полю _index в скриптах

Поле _index представлено виртуально — оно не добавляется в индекс Lucene как реальное поле. Это означает, что вы можете использовать поле _index в запросе term или terms (или любом запросе, который переписывается в запрос term, например, match, query_string или simple_query_string запрос), а также prefix и wildcard запросы. Однако оно не поддерживает regexp и fuzzy запросы.

Запросы к полю _index принимают псевдонимы индексов помимо конкретных имен индексов.

При указании имени удаленного индекса, такого как cluster_1:index_3, запрос должен содержать разделительный символ :. Например, запрос wildcard по полю cluster_*:index_3 будет соответствовать документам из удаленного индекса. Однако запрос по полю cluster*index_1 сопоставляется только с локальными индексами, поскольку разделитель отсутствует. Это поведение соответствует обычным правилам разрешения имен удаленных индексов.

© 2023-2025 Elasticsearch
As of September 2024, Elasticsearch is available under a choice of three licenses: the Server Side Public License (SSPL), the Elastic License, or the AGPLv3 (OSI approved).
Elasticsearch and the Elasticsearch logo are trademarks of Elasticsearch B.V., registered in the U.S. and in other countries.
https://www.elastic.co/guide/en/elasticsearch/reference/8.17/mapping-index-field.html

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API