Динамическое картирование полей
Когда Elasticsearch обнаруживает новое поле в документе, оно динамически добавляет поле в отображение типа по умолчанию. Параметр dynamic управляет этим поведением.
Вы можете явно указать Elasticsearch на динамическое создание полей на основе входящих документов, установив параметр dynamic в true или runtime. При включенном динамическом отображении полей Elasticsearch использует правила в следующей таблице для определения того, как отображать типы данных для каждого поля.
Типы данных полей в следующей таблице — единственные типы данных полей, которые Elasticsearch обнаруживает динамически. Вы должны явно отобразить все другие типы данных.
Тип данных Elasticsearch | ||
Тип данных JSON |
|
|
| Поле не добавлено | Поле не добавлено |
|
|
|
|
|
|
|
|
|
|
| Поле не добавлено |
| Зависит от первого не- | Зависит от первого не- |
|
|
|
|
|
|
|
|
|
Вы можете отключить динамическое отображение как на уровне документа, так и на уровне object. Установка параметра dynamic в false игнорирует новые поля, а strict отклоняет документ, если Elasticsearch встречает неизвестное поле.
Используйте API обновления отображения для обновления параметра dynamic для существующих полей.
Вы можете настроить правила динамического отображения полей для детектирования дат и детектирования чисел. Для определения настраиваемых правил отображения, которые вы можете применить к дополнительным динамическим полям, используйте dynamic_templates.
Детектирование дат
Если date_detection включено (по умолчанию), новые строковые поля проверяются на соответствие любому из шаблонов дат, указанных в dynamic_date_formats. Если совпадение найдено, добавляется новое поле date с соответствующим форматом.
Значение по умолчанию для dynamic_date_formats:
[ "strict_date_optional_time","yyyy/MM/dd HH:mm:ss Z||yyyy/MM/dd Z"]
Например:
resp = client.index(
index="my-index-000001",
id="1",
document={
"create_date": "2015/09/02"
},
)
print(resp)
resp1 = client.indices.get_mapping(
index="my-index-000001",
)
print(resp1) response = client.index(
index: 'my-index-000001',
id: 1,
body: {
create_date: '2015/09/02'
}
)
puts response
response = client.indices.get_mapping(
index: 'my-index-000001'
)
puts response const response = await client.index({
index: "my-index-000001",
id: 1,
document: {
create_date: "2015/09/02",
},
});
console.log(response);
const response1 = await client.indices.getMapping({
index: "my-index-000001",
});
console.log(response1); PUT my-index-000001/_doc/1
{
"create_date": "2015/09/02"
}
GET my-index-000001/_mapping Отключение детектирования дат
Динамическое детектирование дат можно отключить, установив date_detection в false:
resp = client.indices.create(
index="my-index-000001",
mappings={
"date_detection": False
},
)
print(resp)
resp1 = client.index(
index="my-index-000001",
id="1",
document={
"create_date": "2015/09/02"
},
)
print(resp1) response = client.indices.create(
index: 'my-index-000001',
body: {
mappings: {
date_detection: false
}
}
)
puts response
response = client.index(
index: 'my-index-000001',
id: 1,
body: {
create_date: '2015/09/02'
}
)
puts response const response = await client.indices.create({
index: "my-index-000001",
mappings: {
date_detection: false,
},
});
console.log(response);
const response1 = await client.index({
index: "my-index-000001",
id: 1,
document: {
create_date: "2015/09/02",
},
});
console.log(response1); PUT my-index-000001
{
"mappings": {
"date_detection": false
}
}
PUT my-index-000001/_doc/1
{
"create_date": "2015/09/02"
} | Поле |
Настройка форматов дат
В качестве альтернативы, dynamic_date_formats можно настроить для поддержки собственных форматов дат:
resp = client.indices.create(
index="my-index-000001",
mappings={
"dynamic_date_formats": [
"MM/dd/yyyy"
]
},
)
print(resp)
resp1 = client.index(
index="my-index-000001",
id="1",
document={
"create_date": "09/25/2015"
},
)
print(resp1) response = client.indices.create(
index: 'my-index-000001',
body: {
mappings: {
dynamic_date_formats: [
'MM/dd/yyyy'
]
}
}
)
puts response
response = client.index(
index: 'my-index-000001',
id: 1,
body: {
create_date: '09/25/2015'
}
)
puts response const response = await client.indices.create({
index: "my-index-000001",
mappings: {
dynamic_date_formats: ["MM/dd/yyyy"],
},
});
console.log(response);
const response1 = await client.index({
index: "my-index-000001",
id: 1,
document: {
create_date: "09/25/2015",
},
});
console.log(response1); PUT my-index-000001
{
"mappings": {
"dynamic_date_formats": ["MM/dd/yyyy"]
}
}
PUT my-index-000001/_doc/1
{
"create_date": "09/25/2015"
} Есть разница между конфигурацией массива шаблонов дат и конфигурацией нескольких шаблонов в одной строке, разделенных ||. Когда вы настраиваете массив шаблонов дат, шаблон, который соответствует дате в первом документе с непоставленным полем даты, определяет отображение этого поля:
resp = client.indices.create(
index="my-index-000001",
mappings={
"dynamic_date_formats": [
"yyyy/MM",
"MM/dd/yyyy"
]
},
)
print(resp)
resp1 = client.index(
index="my-index-000001",
id="1",
document={
"create_date": "09/25/2015"
},
)
print(resp1) response = client.indices.create(
index: 'my-index-000001',
body: {
mappings: {
dynamic_date_formats: [
'yyyy/MM',
'MM/dd/yyyy'
]
}
}
)
puts response
response = client.index(
index: 'my-index-000001',
id: 1,
body: {
create_date: '09/25/2015'
}
)
puts response const response = await client.indices.create({
index: "my-index-000001",
mappings: {
dynamic_date_formats: ["yyyy/MM", "MM/dd/yyyy"],
},
});
console.log(response);
const response1 = await client.index({
index: "my-index-000001",
id: 1,
document: {
create_date: "09/25/2015",
},
});
console.log(response1); PUT my-index-000001
{
"mappings": {
"dynamic_date_formats": [ "yyyy/MM", "MM/dd/yyyy"]
}
}
PUT my-index-000001/_doc/1
{
"create_date": "09/25/2015"
} Результат отображения будет:
{
"my-index-000001": {
"mappings": {
"dynamic_date_formats": [
"yyyy/MM",
"MM/dd/yyyy"
],
"properties": {
"create_date": {
"type": "date",
"format": "MM/dd/yyyy"
}
}
}
}
} Конфигурация нескольких шаблонов в одной строке, разделенных ||, приводит к отображению, которое поддерживает любой из форматов дат. Это позволяет вам индексировать документы, использующие разные форматы:
resp = client.indices.create(
index="my-index-000001",
mappings={
"dynamic_date_formats": [
"yyyy/MM||MM/dd/yyyy"
]
},
)
print(resp)
resp1 = client.index(
index="my-index-000001",
id="1",
document={
"create_date": "09/25/2015"
},
)
print(resp1) response = client.indices.create(
index: 'my-index-000001',
body: {
mappings: {
dynamic_date_formats: [
'yyyy/MM||MM/dd/yyyy'
]
}
}
)
puts response
response = client.index(
index: 'my-index-000001',
id: 1,
body: {
create_date: '09/25/2015'
}
)
puts response const response = await client.indices.create({
index: "my-index-000001",
mappings: {
dynamic_date_formats: ["yyyy/MM||MM/dd/yyyy"],
},
});
console.log(response);
const response1 = await client.index({
index: "my-index-000001",
id: 1,
document: {
create_date: "09/25/2015",
},
});
console.log(response1); PUT my-index-000001
{
"mappings": {
"dynamic_date_formats": [ "yyyy/MM||MM/dd/yyyy"]
}
}
PUT my-index-000001/_doc/1
{
"create_date": "09/25/2015"
} Результат отображения будет:
{
"my-index-000001": {
"mappings": {
"dynamic_date_formats": [
"yyyy/MM||MM/dd/yyyy"
],
"properties": {
"create_date": {
"type": "date",
"format": "yyyy/MM||MM/dd/yyyy"
}
}
}
}
} Форматы эпохи (epoch_millis и epoch_second) не поддерживаются как динамические форматы дат.
Детектирование чисел
Хотя JSON поддерживает родные типы данных с плавающей точкой и целыми числами, некоторые приложения или языки могут иногда отображать числа в виде строк. Обычно правильным решением является явное отображение этих полей, но детектирование чисел (которое по умолчанию выключено) можно включить, чтобы сделать это автоматически:
resp = client.indices.create(
index="my-index-000001",
mappings={
"numeric_detection": True
},
)
print(resp)
resp1 = client.index(
index="my-index-000001",
id="1",
document={
"my_float": "1.0",
"my_integer": "1"
},
)
print(resp1) response = client.indices.create(
index: 'my-index-000001',
body: {
mappings: {
numeric_detection: true
}
}
)
puts response
response = client.index(
index: 'my-index-000001',
id: 1,
body: {
my_float: '1.0',
my_integer: '1'
}
)
puts response const response = await client.indices.create({
index: "my-index-000001",
mappings: {
numeric_detection: true,
},
});
console.log(response);
const response1 = await client.index({
index: "my-index-000001",
id: 1,
document: {
my_float: "1.0",
my_integer: "1",
},
});
console.log(response1); PUT my-index-000001
{
"mappings": {
"numeric_detection": true
}
}
PUT my-index-000001/_doc/1
{
"my_float": "1.0",
"my_integer": "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/dynamic-field-mapping.html