Spec-Zone.ru › Elasticsearch 8
›Руководство по Elasticsearch [8.17] ›REST API ›API индексов

API обновления отображения

Новая справка по API

Для получения самых последних данных об API обратитесь к API индексов.

Этот API позволяет:

  • Добавить новые поля в существующий индекс
  • Изменить параметры поиска существующих полей

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

Для потоков данных эти изменения по умолчанию применяются ко всем базовым индексам.

resp = client.indices.put_mapping(
    index="my-index-000001",
    properties={
        "email": {
            "type": "keyword"
        }
    },
)
print(resp)
response = client.indices.put_mapping(
  index: 'my-index-000001',
  body: {
    properties: {
      email: {
        type: 'keyword'
      }
    }
  }
)
puts response
const response = await client.indices.putMapping({
  index: "my-index-000001",
  properties: {
    email: {
      type: "keyword",
    },
  },
});
console.log(response);
PUT /my-index-000001/_mapping
{
  "properties": {
    "email": {
      "type": "keyword"
    }
  }
}

Запрос

PUT /<target>/_mapping

Предварительные условия

  • Если включены функции безопасности Elasticsearch, у вас должна быть manage привилегия index для целевого потока данных, индекса или алиаса.

    [7.9] Устарело в 7.9. Если запрос направлен на индекс или алиас индекса, вы также можете обновить его отображение с помощью create, create_doc, index или write привилегии индекса.

Параметры пути

<target>
(Обязательно, строка) Список потоков данных, индексов и алиасов, разделённых запятыми, используемых для ограничения запроса. Поддерживаются подстановочные знаки (*). Для указания всех потоков данных и индексов опустите этот параметр или используйте * или _all.

Параметры запроса

allow_no_indices

(Необязательно, логическое значение) Если false, запрос возвращает ошибку, если какое-либо подстановочное выражение, алиас индекса или _all значение направлены только на отсутствующие или закрытые индексы. Это поведение применяется даже если запрос направлен на другие открытые индексы. Например, запрос, направленный на foo*,bar*, возвращает ошибку, если индекс начинается с foo, но нет индекса, начинающегося с bar.

По умолчанию false.

expand_wildcards

(Необязательно, строка) Тип индекса, с которым могут совпадать подстановочные знаки. Если запрос может нацеливаться на потоки данных, этот аргумент определяет, соответствуют ли подстановочные выражения скрытым потокам данных. Поддерживаются значения, разделённые запятыми, такие как open,hidden. Допустимые значения:

all
Совпадение с любым потоком данных или индексом, включая скрытые.
open
Совпадение с открытыми, не скрытыми индексами. Также соответствует любому не скрытому потоку данных.
closed
Совпадение с закрытыми, не скрытыми индексами. Также соответствует любому не скрытому потоку данных. Потоки данных не могут быть закрыты.
hidden
Совпадение со скрытыми потоками данных и скрытыми индексами. Должно быть использовано совместно с open, closed или с обоими.
none
Подстановочные знаки не принимаются.

По умолчанию open.

ignore_unavailable
(Необязательно, логическое значение) Если false, запрос возвращает ошибку, если он направлен на отсутствующий или закрытый индекс. По умолчанию false.
master_timeout
(Необязательно, единицы времени) Период ожидания узла-мастера. Если узел-мастер недоступен до истечения таймаута, запрос завершается неудачей и возвращает ошибку. По умолчанию 30s. Также может быть установлен в -1, чтобы указать, что запрос никогда не должен зависать.
timeout
(Необязательно, единицы времени) Период ожидания ответа от всех соответствующих узлов в кластере после обновления метаданных кластера. Если ответ не получен до истечения таймаута, обновление метаданных кластера всё ещё применяется, но ответ будет указывать, что оно не было полностью подтверждено. По умолчанию 30s. Также может быть установлен в -1, чтобы указать, что запрос никогда не должен зависать.
write_index_only
(Необязательно, логическое значение) Если true, отображения применяются только к текущему индексу записи для целевого индекса. По умолчанию false.

Тело запроса

properties

(Обязательно, объект отображения) Отображение поля. Для новых полей это отображение может включать:

  • Название поля
  • Тип данных поля
  • Параметры отображения

Для существующих полей см. Изменение отображения существующего поля.

Примеры

Пример с одним целевым объектом

API обновления сопоставления требует существующий поток данных или индекс. Следующий запрос API создания индекса создания индекса создаёт индекс publications без сопоставления.

$params = [
    'index' => 'publications',
];
$response = $client->indices()->create($params);
resp = client.indices.create(
    index="publications",
)
print(resp)
response = client.indices.create(
  index: 'publications'
)
puts response
res, err := es.Indices.Create("publications")
fmt.Println(res, err)
const response = await client.indices.create({
  index: "publications",
});
console.log(response);
PUT /publications

Следующий запрос API обновления сопоставления добавляет title, новое поле типа text, в индекс publications.

$params = [
    'index' => 'publications',
    'body' => [
        'properties' => [
            'title' => [
                'type' => 'text',
            ],
        ],
    ],
];
$response = $client->indices()->putMapping($params);
resp = client.indices.put_mapping(
    index="publications",
    properties={
        "title": {
            "type": "text"
        }
    },
)
print(resp)
response = client.indices.put_mapping(
  index: 'publications',
  body: {
    properties: {
      title: {
        type: 'text'
      }
    }
  }
)
puts response
res, err := es.Indices.PutMapping(
	[]string{"publications"},
	strings.NewReader(`{
	  "properties": {
	    "title": {
	      "type": "text"
	    }
	  }
	}`),
)
fmt.Println(res, err)
const response = await client.indices.putMapping({
  index: "publications",
  properties: {
    title: {
      type: "text",
    },
  },
});
console.log(response);
PUT /publications/_mapping
{
  "properties": {
    "title":  { "type": "text"}
  }
}

Несколько целевых объектов

API обновления сопоставления может быть применён к нескольким потокам данных или индексам с помощью одного запроса. Например, вы можете обновить сопоставления для индексов my-index-000001 и my-index-000002 одновременно:

resp = client.indices.create(
    index="my-index-000001",
)
print(resp)

resp1 = client.indices.create(
    index="my-index-000002",
)
print(resp1)

resp2 = client.indices.put_mapping(
    index="my-index-000001,my-index-000002",
    properties={
        "user": {
            "properties": {
                "name": {
                    "type": "keyword"
                }
            }
        }
    },
)
print(resp2)
response = client.indices.create(
  index: 'my-index-000001'
)
puts response

response = client.indices.create(
  index: 'my-index-000002'
)
puts response

response = client.indices.put_mapping(
  index: 'my-index-000001,my-index-000002',
  body: {
    properties: {
      user: {
        properties: {
          name: {
            type: 'keyword'
          }
        }
      }
    }
  }
)
puts response
const response = await client.indices.create({
  index: "my-index-000001",
});
console.log(response);

const response1 = await client.indices.create({
  index: "my-index-000002",
});
console.log(response1);

const response2 = await client.indices.putMapping({
  index: "my-index-000001,my-index-000002",
  properties: {
    user: {
      properties: {
        name: {
          type: "keyword",
        },
      },
    },
  },
});
console.log(response2);
# Create the two indices
PUT /my-index-000001
PUT /my-index-000002

# Update both mappings
PUT /my-index-000001,my-index-000002/_mapping
{
  "properties": {
    "user": {
      "properties": {
        "name": {
          "type": "keyword"
        }
      }
    }
  }
}

Добавление новых свойств к существующему полю типа объект

Вы можете использовать API обновления сопоставления для добавления новых свойств к существующему полю типа object. Чтобы увидеть, как это работает, попробуйте следующий пример.

Используйте API создания индекса для создания индекса с полем объекта name и внутренним полем текста first.

resp = client.indices.create(
    index="my-index-000001",
    mappings={
        "properties": {
            "name": {
                "properties": {
                    "first": {
                        "type": "text"
                    }
                }
            }
        }
    },
)
print(resp)
response = client.indices.create(
  index: 'my-index-000001',
  body: {
    mappings: {
      properties: {
        name: {
          properties: {
            first: {
              type: 'text'
            }
          }
        }
      }
    }
  }
)
puts response
res, err := es.Indices.Create(
	"my-index-000001",
	es.Indices.Create.WithBody(strings.NewReader(`{
	  "mappings": {
	    "properties": {
	      "name": {
	        "properties": {
	          "first": {
	            "type": "text"
	          }
	        }
	      }
	    }
	  }
	}`)),
)
fmt.Println(res, err)
const response = await client.indices.create({
  index: "my-index-000001",
  mappings: {
    properties: {
      name: {
        properties: {
          first: {
            type: "text",
          },
        },
      },
    },
  },
});
console.log(response);
PUT /my-index-000001
{
  "mappings": {
    "properties": {
      "name": {
        "properties": {
          "first": {
            "type": "text"
          }
        }
      }
    }
  }
}

Используйте API обновления сопоставления для добавления нового внутреннего поля текста last к полю name.

resp = client.indices.put_mapping(
    index="my-index-000001",
    properties={
        "name": {
            "properties": {
                "last": {
                    "type": "text"
                }
            }
        }
    },
)
print(resp)
response = client.indices.put_mapping(
  index: 'my-index-000001',
  body: {
    properties: {
      name: {
        properties: {
          last: {
            type: 'text'
          }
        }
      }
    }
  }
)
puts response
res, err := es.Indices.PutMapping(
	[]string{"my-index-000001"},
	strings.NewReader(`{
	  "properties": {
	    "name": {
	      "properties": {
	        "last": {
	          "type": "text"
	        }
	      }
	    }
	  }
	}`),
)
fmt.Println(res, err)
const response = await client.indices.putMapping({
  index: "my-index-000001",
  properties: {
    name: {
      properties: {
        last: {
          type: "text",
        },
      },
    },
  },
});
console.log(response);
PUT /my-index-000001/_mapping
{
  "properties": {
    "name": {
      "properties": {
        "last": {
          "type": "text"
        }
      }
    }
  }
}

Добавление полей нескольких типов к существующему полю

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

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

Чтобы увидеть, как это работает, попробуйте следующий пример.

Используйте API создания индекса для создания индекса с полем city text.

resp = client.indices.create(
    index="my-index-000001",
    mappings={
        "properties": {
            "city": {
                "type": "text"
            }
        }
    },
)
print(resp)
response = client.indices.create(
  index: 'my-index-000001',
  body: {
    mappings: {
      properties: {
        city: {
          type: 'text'
        }
      }
    }
  }
)
puts response
res, err := es.Indices.Create(
	"my-index-000001",
	es.Indices.Create.WithBody(strings.NewReader(`{
	  "mappings": {
	    "properties": {
	      "city": {
	        "type": "text"
	      }
	    }
	  }
	}`)),
)
fmt.Println(res, err)
const response = await client.indices.create({
  index: "my-index-000001",
  mappings: {
    properties: {
      city: {
        type: "text",
      },
    },
  },
});
console.log(response);
PUT /my-index-000001
{
  "mappings": {
    "properties": {
      "city": {
        "type": "text"
      }
    }
  }
}

Хотя поля text хорошо подходят для полнотекстового поиска, поля keyword не анализируются и могут быть более эффективными для сортировки или агрегаций.

Используйте API обновления сопоставления для включения поля нескольких типов для поля city. Этот запрос добавляет поле нескольких типов city.raw keyword, которое можно использовать для сортировки.

resp = client.indices.put_mapping(
    index="my-index-000001",
    properties={
        "city": {
            "type": "text",
            "fields": {
                "raw": {
                    "type": "keyword"
                }
            }
        }
    },
)
print(resp)
response = client.indices.put_mapping(
  index: 'my-index-000001',
  body: {
    properties: {
      city: {
        type: 'text',
        fields: {
          raw: {
            type: 'keyword'
          }
        }
      }
    }
  }
)
puts response
res, err := es.Indices.PutMapping(
	[]string{"my-index-000001"},
	strings.NewReader(`{
	  "properties": {
	    "city": {
	      "type": "text",
	      "fields": {
	        "raw": {
	          "type": "keyword"
	        }
	      }
	    }
	  }
	}`),
)
fmt.Println(res, err)
const response = await client.indices.putMapping({
  index: "my-index-000001",
  properties: {
    city: {
      type: "text",
      fields: {
        raw: {
          type: "keyword",
        },
      },
    },
  },
});
console.log(response);
PUT /my-index-000001/_mapping
{
  "properties": {
    "city": {
      "type": "text",
      "fields": {
        "raw": {
          "type": "keyword"
        }
      }
    }
  }
}

Изменение поддерживаемых параметров сопоставления для существующего поля

Документация для каждого параметра сопоставления указывает, можно ли обновить его для существующего поля с помощью API обновления сопоставления. Например, вы можете использовать API обновления сопоставления для обновления параметра ignore_above.

Чтобы увидеть, как это работает, попробуйте следующий пример.

Используйте API создания индекса для создания индекса, содержащего поле user_id keyword. Поле user_id имеет значение параметра ignore_above равное 20.

resp = client.indices.create(
    index="my-index-000001",
    mappings={
        "properties": {
            "user_id": {
                "type": "keyword",
                "ignore_above": 20
            }
        }
    },
)
print(resp)
response = client.indices.create(
  index: 'my-index-000001',
  body: {
    mappings: {
      properties: {
        user_id: {
          type: 'keyword',
          ignore_above: 20
        }
      }
    }
  }
)
puts response
res, err := es.Indices.Create(
	"my-index-000001",
	es.Indices.Create.WithBody(strings.NewReader(`{
	  "mappings": {
	    "properties": {
	      "user_id": {
	        "type": "keyword",
	        "ignore_above": 20
	      }
	    }
	  }
	}`)),
)
fmt.Println(res, err)
const response = await client.indices.create({
  index: "my-index-000001",
  mappings: {
    properties: {
      user_id: {
        type: "keyword",
        ignore_above: 20,
      },
    },
  },
});
console.log(response);
PUT /my-index-000001
{
  "mappings": {
    "properties": {
      "user_id": {
        "type": "keyword",
        "ignore_above": 20
      }
    }
  }
}

Используйте API обновления сопоставления для изменения значения параметра ignore_above на 100.

resp = client.indices.put_mapping(
    index="my-index-000001",
    properties={
        "user_id": {
            "type": "keyword",
            "ignore_above": 100
        }
    },
)
print(resp)
response = client.indices.put_mapping(
  index: 'my-index-000001',
  body: {
    properties: {
      user_id: {
        type: 'keyword',
        ignore_above: 100
      }
    }
  }
)
puts response
res, err := es.Indices.PutMapping(
	[]string{"my-index-000001"},
	strings.NewReader(`{
	  "properties": {
	    "user_id": {
	      "type": "keyword",
	      "ignore_above": 100
	    }
	  }
	}`),
)
fmt.Println(res, err)
const response = await client.indices.putMapping({
  index: "my-index-000001",
  properties: {
    user_id: {
      type: "keyword",
      ignore_above: 100,
    },
  },
});
console.log(response);
PUT /my-index-000001/_mapping
{
  "properties": {
    "user_id": {
      "type": "keyword",
      "ignore_above": 100
    }
  }
}

Изменение сопоставления существующего поля

За исключением поддерживаемых параметров сопоставления, вы не можете изменить сопоставление или тип поля существующего поля. Изменение существующего поля может привести к нарушению данных, которые уже индексированы.

Если вам необходимо изменить сопоставление поля в базовых индексах потока данных, см. Изменение сопоставлений и настроек для потока данных.

Если вам необходимо изменить сопоставление поля в других индексах, создайте новый индекс с правильным сопоставлением и переиндексируйте ваши данные в этот индекс.

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

Используйте API создания индекса для создания индекса с полем user_id с типом поля long.

resp = client.indices.create(
    index="my-index-000001",
    mappings={
        "properties": {
            "user_id": {
                "type": "long"
            }
        }
    },
)
print(resp)
response = client.indices.create(
  index: 'my-index-000001',
  body: {
    mappings: {
      properties: {
        user_id: {
          type: 'long'
        }
      }
    }
  }
)
puts response
const response = await client.indices.create({
  index: "my-index-000001",
  mappings: {
    properties: {
      user_id: {
        type: "long",
      },
    },
  },
});
console.log(response);
PUT /my-index-000001
{
  "mappings" : {
    "properties": {
      "user_id": {
        "type": "long"
      }
    }
  }
}

Используйте API индексации для индексации нескольких документов со значениями поля user_id.

resp = client.index(
    index="my-index-000001",
    refresh="wait_for",
    document={
        "user_id": 12345
    },
)
print(resp)

resp1 = client.index(
    index="my-index-000001",
    refresh="wait_for",
    document={
        "user_id": 12346
    },
)
print(resp1)
response = client.index(
  index: 'my-index-000001',
  refresh: 'wait_for',
  body: {
    user_id: 12_345
  }
)
puts response

response = client.index(
  index: 'my-index-000001',
  refresh: 'wait_for',
  body: {
    user_id: 12_346
  }
)
puts response
const response = await client.index({
  index: "my-index-000001",
  refresh: "wait_for",
  document: {
    user_id: 12345,
  },
});
console.log(response);

const response1 = await client.index({
  index: "my-index-000001",
  refresh: "wait_for",
  document: {
    user_id: 12346,
  },
});
console.log(response1);
POST /my-index-000001/_doc?refresh=wait_for
{
  "user_id" : 12345
}

POST /my-index-000001/_doc?refresh=wait_for
{
  "user_id" : 12346
}

Для изменения поля user_id на тип поля keyword используйте API создания индекса для создания нового индекса с правильным сопоставлением.

resp = client.indices.create(
    index="my-new-index-000001",
    mappings={
        "properties": {
            "user_id": {
                "type": "keyword"
            }
        }
    },
)
print(resp)
response = client.indices.create(
  index: 'my-new-index-000001',
  body: {
    mappings: {
      properties: {
        user_id: {
          type: 'keyword'
        }
      }
    }
  }
)
puts response
const response = await client.indices.create({
  index: "my-new-index-000001",
  mappings: {
    properties: {
      user_id: {
        type: "keyword",
      },
    },
  },
});
console.log(response);
PUT /my-new-index-000001
{
  "mappings" : {
    "properties": {
      "user_id": {
        "type": "keyword"
      }
    }
  }
}

Используйте API переиндексации для копирования документов из старого индекса в новый.

resp = client.reindex(
    source={
        "index": "my-index-000001"
    },
    dest={
        "index": "my-new-index-000001"
    },
)
print(resp)
response = client.reindex(
  body: {
    source: {
      index: 'my-index-000001'
    },
    dest: {
      index: 'my-new-index-000001'
    }
  }
)
puts response
const response = await client.reindex({
  source: {
    index: "my-index-000001",
  },
  dest: {
    index: "my-new-index-000001",
  },
});
console.log(response);
POST /_reindex
{
  "source": {
    "index": "my-index-000001"
  },
  "dest": {
    "index": "my-new-index-000001"
  }
}

Переименование поля

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

Например, используйте API создания индекса, чтобы создать индекс с полем user_identifier.

resp = client.indices.create(
    index="my-index-000001",
    mappings={
        "properties": {
            "user_identifier": {
                "type": "keyword"
            }
        }
    },
)
print(resp)
response = client.indices.create(
  index: 'my-index-000001',
  body: {
    mappings: {
      properties: {
        user_identifier: {
          type: 'keyword'
        }
      }
    }
  }
)
puts response
res, err := es.Indices.Create(
	"my-index-000001",
	es.Indices.Create.WithBody(strings.NewReader(`{
	  "mappings": {
	    "properties": {
	      "user_identifier": {
	        "type": "keyword"
	      }
	    }
	  }
	}`)),
)
fmt.Println(res, err)
const response = await client.indices.create({
  index: "my-index-000001",
  mappings: {
    properties: {
      user_identifier: {
        type: "keyword",
      },
    },
  },
});
console.log(response);
PUT /my-index-000001
{
  "mappings": {
    "properties": {
      "user_identifier": {
        "type": "keyword"
      }
    }
  }
}

Используйте API обновления отображения, чтобы добавить псевдоним поля user_id для существующего поля user_identifier.

resp = client.indices.put_mapping(
    index="my-index-000001",
    properties={
        "user_id": {
            "type": "alias",
            "path": "user_identifier"
        }
    },
)
print(resp)
response = client.indices.put_mapping(
  index: 'my-index-000001',
  body: {
    properties: {
      user_id: {
        type: 'alias',
        path: 'user_identifier'
      }
    }
  }
)
puts response
res, err := es.Indices.PutMapping(
	[]string{"my-index-000001"},
	strings.NewReader(`{
	  "properties": {
	    "user_id": {
	      "type": "alias",
	      "path": "user_identifier"
	    }
	  }
	}`),
)
fmt.Println(res, err)
const response = await client.indices.putMapping({
  index: "my-index-000001",
  properties: {
    user_id: {
      type: "alias",
      path: "user_identifier",
    },
  },
});
console.log(response);
PUT /my-index-000001/_mapping
{
  "properties": {
    "user_id": {
      "type": "alias",
      "path": "user_identifier"
    }
  }
}

© 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/indices-put-mapping.html

Spec-Zone.ru

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