Spec-Zone.ru › Elasticsearch 8
›Elasticsearch Guide [8.17] ›Отображение ›Типы данных полей

Массивы

В Elasticsearch нет отдельного типа данных array. По умолчанию любое поле может содержать ноль или более значений, однако все значения в массиве должны быть одного типа данных. Например:

  • массив строк: [ "one", "two" ]
  • массив целых чисел: [ 1, 2 ]
  • массив массивов: [ 1, [ 2, 3 ]] что эквивалентно [ 1, 2, 3 ]
  • массив объектов: [ { "name": "Mary", "age": 12 }, { "name": "John", "age": 10 }]

Массивы с типом поля object против типа nested

Массивы объектов в Elasticsearch не ведут себя так, как вы ожидаете: запросы могут соответствовать полям разных объектов в массиве, что приводит к непредсказуемым результатам. По умолчанию, массивы объектов сглаживаются во время индексирования. Чтобы убедиться, что запросы соответствуют значениям внутри одного объекта, используйте тип данных nested вместо типа данных object.

Более подробное объяснение этого поведения см. в nested.

При динамическом добавлении поля первое значение в массиве определяет тип поля type. Все последующие значения должны быть того же типа данных или, по крайней мере, должны быть возможным привести последующие значения к одному типу данных.

Массивы с разными типами данных не поддерживаются: [ 10, "some string" ]

Массив может содержать null значений, которые либо заменяются настроенным значением null_value, либо пропускаются совсем. Пустой массив [] обрабатывается как отсутствующее поле — поле без значений.

Для использования массивов в документах ничего предварительно настраивать не нужно, они поддерживаются по умолчанию:

resp = client.index(
    index="my-index-000001",
    id="1",
    document={
        "message": "some arrays in this document...",
        "tags": [
            "elasticsearch",
            "wow"
        ],
        "lists": [
            {
                "name": "prog_list",
                "description": "programming list"
            },
            {
                "name": "cool_list",
                "description": "cool stuff list"
            }
        ]
    },
)
print(resp)

resp1 = client.index(
    index="my-index-000001",
    id="2",
    document={
        "message": "no arrays in this document...",
        "tags": "elasticsearch",
        "lists": {
            "name": "prog_list",
            "description": "programming list"
        }
    },
)
print(resp1)

resp2 = client.search(
    index="my-index-000001",
    query={
        "match": {
            "tags": "elasticsearch"
        }
    },
)
print(resp2)
response = client.index(
  index: 'my-index-000001',
  id: 1,
  body: {
    message: 'some arrays in this document...',
    tags: [
      'elasticsearch',
      'wow'
    ],
    lists: [
      {
        name: 'prog_list',
        description: 'programming list'
      },
      {
        name: 'cool_list',
        description: 'cool stuff list'
      }
    ]
  }
)
puts response

response = client.index(
  index: 'my-index-000001',
  id: 2,
  body: {
    message: 'no arrays in this document...',
    tags: 'elasticsearch',
    lists: {
      name: 'prog_list',
      description: 'programming list'
    }
  }
)
puts response

response = client.search(
  index: 'my-index-000001',
  body: {
    query: {
      match: {
        tags: 'elasticsearch'
      }
    }
  }
)
puts response
{
	res, err := es.Index(
		"my-index-000001",
		strings.NewReader(`{
	  "message": "some arrays in this document...",
	  "tags": [
	    "elasticsearch",
	    "wow"
	  ],
	  "lists": [
	    {
	      "name": "prog_list",
	      "description": "programming list"
	    },
	    {
	      "name": "cool_list",
	      "description": "cool stuff list"
	    }
	  ]
	}`),
		es.Index.WithDocumentID("1"),
		es.Index.WithPretty(),
	)
	fmt.Println(res, err)
}

{
	res, err := es.Index(
		"my-index-000001",
		strings.NewReader(`{
	  "message": "no arrays in this document...",
	  "tags": "elasticsearch",
	  "lists": {
	    "name": "prog_list",
	    "description": "programming list"
	  }
	}`),
		es.Index.WithDocumentID("2"),
		es.Index.WithPretty(),
	)
	fmt.Println(res, err)
}

{
	res, err := es.Search(
		es.Search.WithIndex("my-index-000001"),
		es.Search.WithBody(strings.NewReader(`{
	  "query": {
	    "match": {
	      "tags": "elasticsearch"
	    }
	  }
	}`)),
		es.Search.WithPretty(),
	)
	fmt.Println(res, err)
}
const response = await client.index({
  index: "my-index-000001",
  id: 1,
  document: {
    message: "some arrays in this document...",
    tags: ["elasticsearch", "wow"],
    lists: [
      {
        name: "prog_list",
        description: "programming list",
      },
      {
        name: "cool_list",
        description: "cool stuff list",
      },
    ],
  },
});
console.log(response);

const response1 = await client.index({
  index: "my-index-000001",
  id: 2,
  document: {
    message: "no arrays in this document...",
    tags: "elasticsearch",
    lists: {
      name: "prog_list",
      description: "programming list",
    },
  },
});
console.log(response1);

const response2 = await client.search({
  index: "my-index-000001",
  query: {
    match: {
      tags: "elasticsearch",
    },
  },
});
console.log(response2);
PUT my-index-000001/_doc/1
{
  "message": "some arrays in this document...",
  "tags":  [ "elasticsearch", "wow" ], 
  "lists": [ 
    {
      "name": "prog_list",
      "description": "programming list"
    },
    {
      "name": "cool_list",
      "description": "cool stuff list"
    }
  ]
}

PUT my-index-000001/_doc/2 
{
  "message": "no arrays in this document...",
  "tags":  "elasticsearch",
  "lists": {
    "name": "prog_list",
    "description": "programming list"
  }
}

GET my-index-000001/_search
{
  "query": {
    "match": {
      "tags": "elasticsearch" 
    }
  }
}

Поле tags динамически добавляется как поле string.

Поле lists динамически добавляется как поле object.

Второй документ не содержит массивов, но может быть проиндексирован в те же поля.

Запрос ищет elasticsearch в поле tags и соответствует обоим документам.

Вы можете изменять массивы, используя API обновления.

© 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/array.html

Spec-Zone.ru

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