Базовый полнотекстовый поиск и фильтрация в Elasticsearch
Это практическое введение в основы полного поиска по тексту с Elasticsearch, также известного как лексический поиск, с использованием _search API и Query DSL. Вы также узнаете, как фильтровать данные, чтобы сузить результаты поиска на основе точных критериев.
В этом примере мы реализуем функцию поиска для кулинарного блога. Блог содержит рецепты с различными атрибутами, включая текстовое содержание, категориальные данные и числовые рейтинги.
Цель состоит в том, чтобы создать запросы поиска, которые позволят пользователям:
- Находить рецепты на основе ингредиентов, которые они хотят использовать или избегать
- Определять блюда, подходящие для их диетических потребностей
- Находить рецепты с высокими рейтингами в определенных категориях
- Находить недавние рецепты от их любимых авторов
Для достижения этих целей мы будем использовать различные запросы Elasticsearch для выполнения полнотекстового поиска, применения фильтров и комбинирования нескольких критериев поиска.
Требования
Вам понадобится работающий кластер Elasticsearch вместе с Kibana для использования консоли API Dev Tools. Выполните следующую команду в вашей консоли для настройки локального кластера с одним узлом в Docker:
curl -fsSL https://elastic.co/start-local | sh
Шаг 1: Создание индекса
Создайте индекс cooking_blog для начала:
resp = client.indices.create(
index="cooking_blog",
)
print(resp) const response = await client.indices.create({
index: "cooking_blog",
});
console.log(response); PUT /cooking_blog
Теперь определите отображения для индекса:
resp = client.indices.put_mapping(
index="cooking_blog",
properties={
"title": {
"type": "text",
"analyzer": "standard",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"description": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword"
}
}
},
"author": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword"
}
}
},
"date": {
"type": "date",
"format": "yyyy-MM-dd"
},
"category": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword"
}
}
},
"tags": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword"
}
}
},
"rating": {
"type": "float"
}
},
)
print(resp) const response = await client.indices.putMapping({
index: "cooking_blog",
properties: {
title: {
type: "text",
analyzer: "standard",
fields: {
keyword: {
type: "keyword",
ignore_above: 256,
},
},
},
description: {
type: "text",
fields: {
keyword: {
type: "keyword",
},
},
},
author: {
type: "text",
fields: {
keyword: {
type: "keyword",
},
},
},
date: {
type: "date",
format: "yyyy-MM-dd",
},
category: {
type: "text",
fields: {
keyword: {
type: "keyword",
},
},
},
tags: {
type: "text",
fields: {
keyword: {
type: "keyword",
},
},
},
rating: {
type: "float",
},
},
});
console.log(response); PUT /cooking_blog/_mapping
{
"properties": {
"title": {
"type": "text",
"analyzer": "standard",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"description": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword"
}
}
},
"author": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword"
}
}
},
"date": {
"type": "date",
"format": "yyyy-MM-dd"
},
"category": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword"
}
}
},
"tags": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword"
}
}
},
"rating": {
"type": "float"
}
}
} | Анализатор | |
| Мульти-поля используются здесь для индексации полей | |
| Параметр |
Полнотекстовый поиск работает с помощью анализа текста. Анализ текста нормализует и стандартизирует текстовые данные, чтобы их можно было эффективно хранить в инвертированном индексе и искать в режиме реального времени. Анализ происходит как во время индексирования, так и во время поиска. В этом учебнике не будет подробно рассматриваться анализ, но важно понять, как обрабатывается текст для создания эффективных запросов поиска.
Шаг 2: Добавление примеров постов блога в ваш индекс
Теперь вам нужно индексировать некоторые примеры постов блога с помощью API массовой индексации. Обратите внимание, что поля text анализируются, а мульти-поля генерируются во время индексирования.
resp = client.bulk(
index="cooking_blog",
refresh="wait_for",
operations=[
{
"index": {
"_id": "1"
}
},
{
"title": "Perfect Pancakes: A Fluffy Breakfast Delight",
"description": "Learn the secrets to making the fluffiest pancakes, so amazing you won't believe your tastebuds. This recipe uses buttermilk and a special folding technique to create light, airy pancakes that are perfect for lazy Sunday mornings.",
"author": "Maria Rodriguez",
"date": "2023-05-01",
"category": "Breakfast",
"tags": [
"pancakes",
"breakfast",
"easy recipes"
],
"rating": 4.8
},
{
"index": {
"_id": "2"
}
},
{
"title": "Spicy Thai Green Curry: A Vegetarian Adventure",
"description": "Dive into the flavors of Thailand with this vibrant green curry. Packed with vegetables and aromatic herbs, this dish is both healthy and satisfying. Don't worry about the heat - you can easily adjust the spice level to your liking.",
"author": "Liam Chen",
"date": "2023-05-05",
"category": "Main Course",
"tags": [
"thai",
"vegetarian",
"curry",
"spicy"
],
"rating": 4.6
},
{
"index": {
"_id": "3"
}
},
{
"title": "Classic Beef Stroganoff: A Creamy Comfort Food",
"description": "Indulge in this rich and creamy beef stroganoff. Tender strips of beef in a savory mushroom sauce, served over a bed of egg noodles. It's the ultimate comfort food for chilly evenings.",
"author": "Emma Watson",
"date": "2023-05-10",
"category": "Main Course",
"tags": [
"beef",
"pasta",
"comfort food"
],
"rating": 4.7
},
{
"index": {
"_id": "4"
}
},
{
"title": "Vegan Chocolate Avocado Mousse",
"description": "Discover the magic of avocado in this rich, vegan chocolate mousse. Creamy, indulgent, and secretly healthy, it's the perfect guilt-free dessert for chocolate lovers.",
"author": "Alex Green",
"date": "2023-05-15",
"category": "Dessert",
"tags": [
"vegan",
"chocolate",
"avocado",
"healthy dessert"
],
"rating": 4.5
},
{
"index": {
"_id": "5"
}
},
{
"title": "Crispy Oven-Fried Chicken",
"description": "Get that perfect crunch without the deep fryer! This oven-fried chicken recipe delivers crispy, juicy results every time. A healthier take on the classic comfort food.",
"author": "Maria Rodriguez",
"date": "2023-05-20",
"category": "Main Course",
"tags": [
"chicken",
"oven-fried",
"healthy"
],
"rating": 4.9
}
],
)
print(resp) const response = await client.bulk({
index: "cooking_blog",
refresh: "wait_for",
operations: [
{
index: {
_id: "1",
},
},
{
title: "Perfect Pancakes: A Fluffy Breakfast Delight",
description:
"Learn the secrets to making the fluffiest pancakes, so amazing you won't believe your tastebuds. This recipe uses buttermilk and a special folding technique to create light, airy pancakes that are perfect for lazy Sunday mornings.",
author: "Maria Rodriguez",
date: "2023-05-01",
category: "Breakfast",
tags: ["pancakes", "breakfast", "easy recipes"],
rating: 4.8,
},
{
index: {
_id: "2",
},
},
{
title: "Spicy Thai Green Curry: A Vegetarian Adventure",
description:
"Dive into the flavors of Thailand with this vibrant green curry. Packed with vegetables and aromatic herbs, this dish is both healthy and satisfying. Don't worry about the heat - you can easily adjust the spice level to your liking.",
author: "Liam Chen",
date: "2023-05-05",
category: "Main Course",
tags: ["thai", "vegetarian", "curry", "spicy"],
rating: 4.6,
},
{
index: {
_id: "3",
},
},
{
title: "Classic Beef Stroganoff: A Creamy Comfort Food",
description:
"Indulge in this rich and creamy beef stroganoff. Tender strips of beef in a savory mushroom sauce, served over a bed of egg noodles. It's the ultimate comfort food for chilly evenings.",
author: "Emma Watson",
date: "2023-05-10",
category: "Main Course",
tags: ["beef", "pasta", "comfort food"],
rating: 4.7,
},
{
index: {
_id: "4",
},
},
{
title: "Vegan Chocolate Avocado Mousse",
description:
"Discover the magic of avocado in this rich, vegan chocolate mousse. Creamy, indulgent, and secretly healthy, it's the perfect guilt-free dessert for chocolate lovers.",
author: "Alex Green",
date: "2023-05-15",
category: "Dessert",
tags: ["vegan", "chocolate", "avocado", "healthy dessert"],
rating: 4.5,
},
{
index: {
_id: "5",
},
},
{
title: "Crispy Oven-Fried Chicken",
description:
"Get that perfect crunch without the deep fryer! This oven-fried chicken recipe delivers crispy, juicy results every time. A healthier take on the classic comfort food.",
author: "Maria Rodriguez",
date: "2023-05-20",
category: "Main Course",
tags: ["chicken", "oven-fried", "healthy"],
rating: 4.9,
},
],
});
console.log(response); POST /cooking_blog/_bulk?refresh=wait_for
{"index":{"_id":"1"}}
{"title":"Perfect Pancakes: A Fluffy Breakfast Delight","description":"Learn the secrets to making the fluffiest pancakes, so amazing you won't believe your tastebuds. This recipe uses buttermilk and a special folding technique to create light, airy pancakes that are perfect for lazy Sunday mornings.","author":"Maria Rodriguez","date":"2023-05-01","category":"Breakfast","tags":["pancakes","breakfast","easy recipes"],"rating":4.8}
{"index":{"_id":"2"}}
{"title":"Spicy Thai Green Curry: A Vegetarian Adventure","description":"Dive into the flavors of Thailand with this vibrant green curry. Packed with vegetables and aromatic herbs, this dish is both healthy and satisfying. Don't worry about the heat - you can easily adjust the spice level to your liking.","author":"Liam Chen","date":"2023-05-05","category":"Main Course","tags":["thai","vegetarian","curry","spicy"],"rating":4.6}
{"index":{"_id":"3"}}
{"title":"Classic Beef Stroganoff: A Creamy Comfort Food","description":"Indulge in this rich and creamy beef stroganoff. Tender strips of beef in a savory mushroom sauce, served over a bed of egg noodles. It's the ultimate comfort food for chilly evenings.","author":"Emma Watson","date":"2023-05-10","category":"Main Course","tags":["beef","pasta","comfort food"],"rating":4.7}
{"index":{"_id":"4"}}
{"title":"Vegan Chocolate Avocado Mousse","description":"Discover the magic of avocado in this rich, vegan chocolate mousse. Creamy, indulgent, and secretly healthy, it's the perfect guilt-free dessert for chocolate lovers.","author":"Alex Green","date":"2023-05-15","category":"Dessert","tags":["vegan","chocolate","avocado","healthy dessert"],"rating":4.5}
{"index":{"_id":"5"}}
{"title":"Crispy Oven-Fried Chicken","description":"Get that perfect crunch without the deep fryer! This oven-fried chicken recipe delivers crispy, juicy results every time. A healthier take on the classic comfort food.","author":"Maria Rodriguez","date":"2023-05-20","category":"Main Course","tags":["chicken","oven-fried","healthy"],"rating":4.9} Шаг 3: Выполнение основных полнотекстовых поисков
Полнотекстовый поиск включает в себя выполнение текстовых запросов по одному или нескольким полям документов. Эти запросы вычисляют релевантность каждого соответствующего документа на основе того, насколько содержание документа соответствует поисковым фразам. Elasticsearch предлагает различные типы запросов, каждый из которых имеет свой собственный метод сопоставления текста и оценок релевантности.
match запрос
Запрос match является стандартным запросом для полнотекстового или «лексического» поиска. Текст запроса будет анализироваться в соответствии с конфигурацией анализатора, указанной для каждого поля (или во время поиска).
Сначала выполните поиск по полю description по фразе "fluffy pancakes":
resp = client.search(
index="cooking_blog",
query={
"match": {
"description": {
"query": "fluffy pancakes"
}
}
},
)
print(resp) const response = await client.search({
index: "cooking_blog",
query: {
match: {
description: {
query: "fluffy pancakes",
},
},
},
});
console.log(response); GET /cooking_blog/_search
{
"query": {
"match": {
"description": {
"query": "fluffy pancakes"
}
}
}
} | По умолчанию запрос |
Во время поиска Elasticsearch использует анализатор, определённый в отображении поля. В этом примере мы используем анализатор standard. Использование другого анализатора во время поиска — это случай расширенного использования.
Пример ответа
{
"took": 0,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 1,
"relation": "eq"
},
"max_score": 1.8378843,
"hits": [
{
"_index": "cooking_blog",
"_id": "1",
"_score": 1.8378843,
"_source": {
"title": "Perfect Pancakes: A Fluffy Breakfast Delight",
"description": "Learn the secrets to making the fluffiest pancakes, so amazing you won't believe your tastebuds. This recipe uses buttermilk and a special folding technique to create light, airy pancakes that are perfect for lazy Sunday mornings.",
"author": "Maria Rodriguez",
"date": "2023-05-01",
"category": "Breakfast",
"tags": [
"pancakes",
"breakfast",
"easy recipes"
],
"rating": 4.8
}
}
]
}
} | Объект | |
|
| |
|
| |
| Заголовок содержит как "Fluffy", так и "Pancakes", что точно соответствует нашим поисковым фразам. | |
| Описание включает "fluffiest" и "pancakes", что ещё больше повышает релевантность документа благодаря процессу анализа. |
Требование всех терминов в запросе match
Укажите оператор and, чтобы потребовать оба термина в поле description. Этот более строгий поиск возвращает ноль совпадений в наших тестовых данных, так как ни один документ не содержит и "fluffy", и "pancakes" в описании.
resp = client.search(
index="cooking_blog",
query={
"match": {
"description": {
"query": "fluffy pancakes",
"operator": "and"
}
}
},
)
print(resp) const response = await client.search({
index: "cooking_blog",
query: {
match: {
description: {
query: "fluffy pancakes",
operator: "and",
},
},
},
});
console.log(response); GET /cooking_blog/_search
{
"query": {
"match": {
"description": {
"query": "fluffy pancakes",
"operator": "and"
}
}
}
} Пример ответа
{
"took": 0,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 0,
"relation": "eq"
},
"max_score": null,
"hits": []
}
} Укажите минимальное количество терминов для соответствия
Используйте параметр minimum_should_match, чтобы указать минимальное количество терминов, которые должен содержать документ, чтобы он был включен в результаты поиска.
Выполните поиск по полю title, чтобы соответствовать как минимум 2 из 3 терминов: "fluffy", "pancakes", или "breakfast". Это полезно для повышения релевантности, позволяя некоторую гибкость.
resp = client.search(
index="cooking_blog",
query={
"match": {
"title": {
"query": "fluffy pancakes breakfast",
"minimum_should_match": 2
}
}
},
)
print(resp) const response = await client.search({
index: "cooking_blog",
query: {
match: {
title: {
query: "fluffy pancakes breakfast",
minimum_should_match: 2,
},
},
},
});
console.log(response); GET /cooking_blog/_search
{
"query": {
"match": {
"title": {
"query": "fluffy pancakes breakfast",
"minimum_should_match": 2
}
}
}
} Шаг 4: Поиск по нескольким полям одновременно
Когда пользователи вводят поисковый запрос, они часто не знают (или не заботятся) о том, в каком конкретном поле находятся их поисковые термины. Запрос multi_match позволяет одновременно искать по нескольким полям.
Давайте начнем с базового запроса multi_match:
resp = client.search(
index="cooking_blog",
query={
"multi_match": {
"query": "vegetarian curry",
"fields": [
"title",
"description",
"tags"
]
}
},
)
print(resp) const response = await client.search({
index: "cooking_blog",
query: {
multi_match: {
query: "vegetarian curry",
fields: ["title", "description", "tags"],
},
},
});
console.log(response); GET /cooking_blog/_search
{
"query": {
"multi_match": {
"query": "vegetarian curry",
"fields": ["title", "description", "tags"]
}
}
} Этот запрос ищет "vegetarian curry" по полям title, description и tags. Каждое поле имеет одинаковый вес.
Однако во многих случаях соответствия в определенных полях (например, в заголовке) могут быть более релевантными, чем другие. Мы можем настроить важность каждого поля с помощью повышения поля:
resp = client.search(
index="cooking_blog",
query={
"multi_match": {
"query": "vegetarian curry",
"fields": [
"title^3",
"description^2",
"tags"
]
}
},
)
print(resp) const response = await client.search({
index: "cooking_blog",
query: {
multi_match: {
query: "vegetarian curry",
fields: ["title^3", "description^2", "tags"],
},
},
});
console.log(response); GET /cooking_blog/_search
{
"query": {
"multi_match": {
"query": "vegetarian curry",
"fields": ["title^3", "description^2", "tags"]
}
}
} | Синтаксис
|
Подробнее о полях и усилении по полям в справочнике по запросу multi_match.
Пример ответа
{
"took": 0,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 1,
"relation": "eq"
},
"max_score": 7.546015,
"hits": [
{
"_index": "cooking_blog",
"_id": "2",
"_score": 7.546015,
"_source": {
"title": "Spicy Thai Green Curry: A Vegetarian Adventure",
"description": "Dive into the flavors of Thailand with this vibrant green curry. Packed with vegetables and aromatic herbs, this dish is both healthy and satisfying. Don't worry about the heat - you can easily adjust the spice level to your liking.",
"author": "Liam Chen",
"date": "2023-05-05",
"category": "Main Course",
"tags": [
"thai",
"vegetarian",
"curry",
"spicy"
],
"rating": 4.6
}
}
]
}
} | Заголовок содержит «Вегетарианский» и «Карри», что соответствует нашим поисковым терминам. Поле заголовка имеет наибольшее усиление (^3), что значительно влияет на рейтинг релевантности этого документа. | |
| Описание содержит «карри» и связанные термины, такие как «овощи», что ещё больше повышает релевантность документа. | |
| Теги включают «вегетарианский» и «карри», что обеспечивает точное соответствие нашим поисковым терминам, хотя без усиления. |
Этот результат демонстрирует, как запрос multi_match с усилением по полям помогает пользователям находить релевантные рецепты по нескольким полям. Даже если точная фраза «вегетарианское карри» не появляется ни в одном поле, сочетание совпадений по нескольким полям приводит к очень релевантному результату.
Запрос multi_match часто рекомендуется вместо одиночного запроса match для большинства случаев использования поиска по тексту, так как он обеспечивает большую гибкость и лучше соответствует ожиданиям пользователя.
Шаг 5: Фильтр и поиск точных совпадений
Фильтрование позволяет сузить результаты поиска на основе точных критериев. В отличие от полнотекстового поиска, фильтры двоичные (да/нет) и не влияют на рейтинг релевантности. Фильтры выполняются быстрее, чем запросы, поскольку исключенные результаты не нужно оценивать.
Этот запрос bool вернёт только посты блога в категории «Завтрак».
resp = client.search(
index="cooking_blog",
query={
"bool": {
"filter": [
{
"term": {
"category.keyword": "Breakfast"
}
}
]
}
},
)
print(resp) const response = await client.search({
index: "cooking_blog",
query: {
bool: {
filter: [
{
term: {
"category.keyword": "Breakfast",
},
},
],
},
},
});
console.log(response); GET /cooking_blog/_search
{
"query": {
"bool": {
"filter": [
{ "term": { "category.keyword": "Breakfast" } }
]
}
}
} | Обратите внимание на использование |
Суффикс .keyword обращается к неунализированной версии поля, что позволяет осуществлять точное, чувствительное к регистру сопоставление. Это работает в двух сценариях:
- При использовании динамической схемы для текстовых полей. Elasticsearch автоматически создаёт подполе
.keyword. - При явном отображении текстовых полей с подполем
.keyword. Например, мы явно отобразили полеcategoryв шаге 1 этого руководства.
Поиск записей в диапазоне дат
Часто пользователи хотят найти контент, опубликованный в определённый период времени. Запрос range находит документы, которые попадают в числовые или временные диапазоны.
resp = client.search(
index="cooking_blog",
query={
"range": {
"date": {
"gte": "2023-05-01",
"lte": "2023-05-31"
}
}
},
)
print(resp) const response = await client.search({
index: "cooking_blog",
query: {
range: {
date: {
gte: "2023-05-01",
lte: "2023-05-31",
},
},
},
});
console.log(response); GET /cooking_blog/_search
{
"query": {
"range": {
"date": {
"gte": "2023-05-01",
"lte": "2023-05-31"
}
}
}
} | Больше или равно 1 мая 2023 года. | |
| Меньше или равно 31 мая 2023 года. |
Поиск точных совпадений
Иногда пользователи хотят искать точные термины, чтобы устранить неоднозначность в результатах поиска. Запрос term ищет точный термин в поле без анализа. Точные, чувствительные к регистру совпадения по конкретным терминам часто называют поиском «по ключевым словам».
Здесь вы будете искать автора «Мария Родригес» в поле author.keyword.
resp = client.search(
index="cooking_blog",
query={
"term": {
"author.keyword": "Maria Rodriguez"
}
},
)
print(resp) const response = await client.search({
index: "cooking_blog",
query: {
term: {
"author.keyword": "Maria Rodriguez",
},
},
});
console.log(response); GET /cooking_blog/_search
{
"query": {
"term": {
"author.keyword": "Maria Rodriguez"
}
}
} | Запрос |
Избегайте использования запроса term для text полей, поскольку они преобразуются в процессе анализа.
Шаг 6: Объединение нескольких критериев поиска
Запрос bool позволяет объединять несколько условий запроса для создания сложных поисков. В данном сценарии обучающего руководства это полезно, когда у пользователей есть сложные требования к поиску рецептов.
Давайте создадим запрос, который удовлетворяет следующим потребностям пользователя:
- Должен быть вегетарианский рецепт
- Должен содержать «карри» или «острый» в названии или описании
- Должен быть основным блюдом
- Не должен быть десертом
- Должен иметь рейтинг не ниже 4,5
- Лучше всего рецепты, опубликованные в прошлом месяце
resp = client.search(
index="cooking_blog",
query={
"bool": {
"must": [
{
"term": {
"tags": "vegetarian"
}
},
{
"range": {
"rating": {
"gte": 4.5
}
}
}
],
"should": [
{
"term": {
"category": "Main Course"
}
},
{
"multi_match": {
"query": "curry spicy",
"fields": [
"title^2",
"description"
]
}
},
{
"range": {
"date": {
"gte": "now-1M/d"
}
}
}
],
"must_not": [
{
"term": {
"category.keyword": "Dessert"
}
}
]
}
},
)
print(resp) const response = await client.search({
index: "cooking_blog",
query: {
bool: {
must: [
{
term: {
tags: "vegetarian",
},
},
{
range: {
rating: {
gte: 4.5,
},
},
},
],
should: [
{
term: {
category: "Main Course",
},
},
{
multi_match: {
query: "curry spicy",
fields: ["title^2", "description"],
},
},
{
range: {
date: {
gte: "now-1M/d",
},
},
},
],
must_not: [
{
term: {
"category.keyword": "Dessert",
},
},
],
},
},
});
console.log(response); GET /cooking_blog/_search
{
"query": {
"bool": {
"must": [
{ "term": { "tags": "vegetarian" } },
{
"range": {
"rating": {
"gte": 4.5
}
}
}
],
"should": [
{
"term": {
"category": "Main Course"
}
},
{
"multi_match": {
"query": "curry spicy",
"fields": [
"title^2",
"description"
]
}
},
{
"range": {
"date": {
"gte": "now-1M/d"
}
}
}
],
"must_not": [
{
"term": {
"category.keyword": "Dessert"
}
}
]
}
}
} | Условие |
Пример ответа
{
"took": 1,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 1,
"relation": "eq"
},
"max_score": 7.444513,
"hits": [
{
"_index": "cooking_blog",
"_id": "2",
"_score": 7.444513,
"_source": {
"title": "Spicy Thai Green Curry: A Vegetarian Adventure",
"description": "Dive into the flavors of Thailand with this vibrant green curry. Packed with vegetables and aromatic herbs, this dish is both healthy and satisfying. Don't worry about the heat - you can easily adjust the spice level to your liking.",
"author": "Liam Chen",
"date": "2023-05-05",
"category": "Main Course",
"tags": [
"thai",
"vegetarian",
"curry",
"spicy"
],
"rating": 4.6
}
}
]
}
} | Заголовок содержит «Острый» и «Карри», что соответствует нашему условию «должно содержать». С поведением по умолчанию best_fields это поле вносит наибольший вклад в рейтинг релевантности. | |
| Хотя описание также содержит соответствующие термины, используется только рейтинг лучшего сопоставленного поля по умолчанию. | |
| Рецепт был опубликован в течение последнего месяца, удовлетворяя нашему предпочтению актуальности. | |
| Категория «Основное блюдо» удовлетворяет ещё одному условию | |
| Тег «вегетарианский» удовлетворяет условию | |
| Рейтинг 4,6 соответствует нашему минимальному требованию рейтинга 4,5. |
Дополнительная информация
В этом руководстве были представлены основы полнотекстового поиска и фильтрации в Elasticsearch. Для создания реального поискового опыта необходимо изучить многие более продвинутые концепции и методы. Вот некоторые ресурсы, если вы готовы углубиться в эту тему:
- Полнотекстовый поиск: Узнайте о ключевых компонентах полнотекстового поиска в Elasticsearch.
- Основы Elasticsearch — Поиск и анализ данных: Поймите все ваши возможности для поиска и анализа данных в Elasticsearch.
- Анализ текста: Узнайте, как текст обрабатывается для полнотекстового поиска.
- Поиск ваших данных: Узнайте о более продвинутых методах поиска с использованием API
_search, включая семантический поиск.
© 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/full-text-filter-tutorial.html