Тип поля разреженного вектора
Поле типа sparse_vector может индексировать особенности и веса, чтобы их можно было использовать для запросов к документам с помощью запроса sparse_vector. Это поле также можно использовать с устаревшим запросом text_expansion.
Тип поля sparse_vector следует использовать с отображениями ELSER (отображениями ELSER).
resp = client.indices.create(
index="my-index",
mappings={
"properties": {
"text.tokens": {
"type": "sparse_vector"
}
}
},
)
print(resp) response = client.indices.create(
index: 'my-index',
body: {
mappings: {
properties: {
'text.tokens' => {
type: 'sparse_vector'
}
}
}
}
)
puts response const response = await client.indices.create({
index: "my-index",
mappings: {
properties: {
"text.tokens": {
type: "sparse_vector",
},
},
},
});
console.log(response); PUT my-index
{
"mappings": {
"properties": {
"text.tokens": {
"type": "sparse_vector"
}
}
}
} См. учебник по семантическому поиску с помощью ELSER для полного примера добавления документов в поле отображения sparse_vector с помощью ELSER.
Многозначные разреженные векторы
При передаче массивов значений для разреженных векторов выбирается максимальное значение для аналогичных по имени особенностей.
В статье Adapting Learned Sparse Retrieval for Long Documents (https://arxiv.org/pdf/2305.18494.pdf) это обсуждается более подробно. Вкратце, результаты исследований показывают, что агрегация представлений обычно превосходит агрегацию оценок.
В случаях, когда вам нужны совпадающие имена особенностей, следует хранить их отдельно или использовать вложенные поля.
Ниже приведен пример передачи документа с совпадающими именами особенностей. Предположим, что в этом примере существуют две категории: положительные и отрицательные отзывы. Однако для целей ретрива нам также нужна общая оценка, а не конкретные отзывы. В примере impact хранится как многозначный разреженный вектор, и сохраняются только максимальные значения совпадающих имен. Более конкретно, конечный запрос GET здесь возвращает значение ~1,2 (что является значением max(impact.delicious[0], impact.delicious[1]) и приближенным, так как у нас есть относительная ошибка 0,4%, как поясняется ниже).
resp = client.indices.create(
index="my-index-000001",
mappings={
"properties": {
"text": {
"type": "text",
"analyzer": "standard"
},
"impact": {
"type": "sparse_vector"
},
"positive": {
"type": "sparse_vector"
},
"negative": {
"type": "sparse_vector"
}
}
},
)
print(resp)
resp1 = client.index(
index="my-index-000001",
document={
"text": "I had some terribly delicious carrots.",
"impact": [
{
"I": 0.55,
"had": 0.4,
"some": 0.28,
"terribly": 0.01,
"delicious": 1.2,
"carrots": 0.8
},
{
"I": 0.54,
"had": 0.4,
"some": 0.28,
"terribly": 2.01,
"delicious": 0.02,
"carrots": 0.4
}
],
"positive": {
"I": 0.55,
"had": 0.4,
"some": 0.28,
"terribly": 0.01,
"delicious": 1.2,
"carrots": 0.8
},
"negative": {
"I": 0.54,
"had": 0.4,
"some": 0.28,
"terribly": 2.01,
"delicious": 0.02,
"carrots": 0.4
}
},
)
print(resp1)
resp2 = client.search(
index="my-index-000001",
query={
"term": {
"impact": {
"value": "delicious"
}
}
},
)
print(resp2) const response = await client.indices.create({
index: "my-index-000001",
mappings: {
properties: {
text: {
type: "text",
analyzer: "standard",
},
impact: {
type: "sparse_vector",
},
positive: {
type: "sparse_vector",
},
negative: {
type: "sparse_vector",
},
},
},
});
console.log(response);
const response1 = await client.index({
index: "my-index-000001",
document: {
text: "I had some terribly delicious carrots.",
impact: [
{
I: 0.55,
had: 0.4,
some: 0.28,
terribly: 0.01,
delicious: 1.2,
carrots: 0.8,
},
{
I: 0.54,
had: 0.4,
some: 0.28,
terribly: 2.01,
delicious: 0.02,
carrots: 0.4,
},
],
positive: {
I: 0.55,
had: 0.4,
some: 0.28,
terribly: 0.01,
delicious: 1.2,
carrots: 0.8,
},
negative: {
I: 0.54,
had: 0.4,
some: 0.28,
terribly: 2.01,
delicious: 0.02,
carrots: 0.4,
},
},
});
console.log(response1);
const response2 = await client.search({
index: "my-index-000001",
query: {
term: {
impact: {
value: "delicious",
},
},
},
});
console.log(response2); PUT my-index-000001
{
"mappings": {
"properties": {
"text": {
"type": "text",
"analyzer": "standard"
},
"impact": {
"type": "sparse_vector"
},
"positive": {
"type": "sparse_vector"
},
"negative": {
"type": "sparse_vector"
}
}
}
}
POST my-index-000001/_doc
{
"text": "I had some terribly delicious carrots.",
"impact": [{"I": 0.55, "had": 0.4, "some": 0.28, "terribly": 0.01, "delicious": 1.2, "carrots": 0.8},
{"I": 0.54, "had": 0.4, "some": 0.28, "terribly": 2.01, "delicious": 0.02, "carrots": 0.4}],
"positive": {"I": 0.55, "had": 0.4, "some": 0.28, "terribly": 0.01, "delicious": 1.2, "carrots": 0.8},
"negative": {"I": 0.54, "had": 0.4, "some": 0.28, "terribly": 2.01, "delicious": 0.02, "carrots": 0.4}
}
GET my-index-000001/_search
{
"query": {
"term": {
"impact": {
"value": "delicious"
}
}
}
} Поля типа sparse_vector не могут быть включены в индексы, которые были созданы в Elasticsearch версий от 8.0 до 8.10.
Поля типа sparse_vector поддерживают только строго положительные значения. Отрицательные значения будут отклонены.
Поля типа sparse_vector не поддерживают анализаторы, запросы, сортировку или агрегирование. Они могут использоваться только в специализированных запросах. Рекомендуемым запросом для этих полей являются запросы sparse_vector. Они также могут использоваться в устаревших запросах text_expansion.
Поля типа sparse_vector сохраняют 9 значимых битов для точности, что соответствует относительной ошибке около 0,4%.
© 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/sparse-vector.html