Тип поля boolean
Поля типа boolean принимают JSON true и false значения, но также могут принимать строки, которые интерпретируются как true или false:
| Ложные значения | |
| Истинные значения | |
Например:
resp = client.indices.create(
index="my-index-000001",
mappings={
"properties": {
"is_published": {
"type": "boolean"
}
}
},
)
print(resp)
resp1 = client.index(
index="my-index-000001",
id="1",
refresh=True,
document={
"is_published": "true"
},
)
print(resp1)
resp2 = client.search(
index="my-index-000001",
query={
"term": {
"is_published": True
}
},
)
print(resp2) response = client.indices.create(
index: 'my-index-000001',
body: {
mappings: {
properties: {
is_published: {
type: 'boolean'
}
}
}
}
)
puts response
response = client.index(
index: 'my-index-000001',
id: 1,
refresh: true,
body: {
is_published: 'true'
}
)
puts response
response = client.search(
index: 'my-index-000001',
body: {
query: {
term: {
is_published: true
}
}
}
)
puts response const response = await client.indices.create({
index: "my-index-000001",
mappings: {
properties: {
is_published: {
type: "boolean",
},
},
},
});
console.log(response);
const response1 = await client.index({
index: "my-index-000001",
id: 1,
refresh: "true",
document: {
is_published: "true",
},
});
console.log(response1);
const response2 = await client.search({
index: "my-index-000001",
query: {
term: {
is_published: true,
},
},
});
console.log(response2); PUT my-index-000001
{
"mappings": {
"properties": {
"is_published": {
"type": "boolean"
}
}
}
}
POST my-index-000001/_doc/1?refresh
{
"is_published": "true"
}
GET my-index-000001/_search
{
"query": {
"term": {
"is_published": true
}
}
} | Индексирование документа с | |
| Поиск документов со значением JSON |
Агрегации, такие как terms агрегация, используют 1 и 0 для key, и строки "true" и "false" для key_as_string. Поля типа boolean, используемые в скриптах, возвращают true и false:
resp = client.index(
index="my-index-000001",
id="1",
refresh=True,
document={
"is_published": True
},
)
print(resp)
resp1 = client.index(
index="my-index-000001",
id="2",
refresh=True,
document={
"is_published": False
},
)
print(resp1)
resp2 = client.search(
index="my-index-000001",
aggs={
"publish_state": {
"terms": {
"field": "is_published"
}
}
},
sort=[
"is_published"
],
fields=[
{
"field": "weight"
}
],
runtime_mappings={
"weight": {
"type": "long",
"script": "emit(doc['is_published'].value ? 10 : 0)"
}
},
)
print(resp2) response = client.index(
index: 'my-index-000001',
id: 1,
refresh: true,
body: {
is_published: true
}
)
puts response
response = client.index(
index: 'my-index-000001',
id: 2,
refresh: true,
body: {
is_published: false
}
)
puts response
response = client.search(
index: 'my-index-000001',
body: {
aggregations: {
publish_state: {
terms: {
field: 'is_published'
}
}
},
sort: [
'is_published'
],
fields: [
{
field: 'weight'
}
],
runtime_mappings: {
weight: {
type: 'long',
script: "emit(doc['is_published'].value ? 10 : 0)"
}
}
}
)
puts response const response = await client.index({
index: "my-index-000001",
id: 1,
refresh: "true",
document: {
is_published: true,
},
});
console.log(response);
const response1 = await client.index({
index: "my-index-000001",
id: 2,
refresh: "true",
document: {
is_published: false,
},
});
console.log(response1);
const response2 = await client.search({
index: "my-index-000001",
aggs: {
publish_state: {
terms: {
field: "is_published",
},
},
},
sort: ["is_published"],
fields: [
{
field: "weight",
},
],
runtime_mappings: {
weight: {
type: "long",
script: "emit(doc['is_published'].value ? 10 : 0)",
},
},
});
console.log(response2); POST my-index-000001/_doc/1?refresh
{
"is_published": true
}
POST my-index-000001/_doc/2?refresh
{
"is_published": false
}
GET my-index-000001/_search
{
"aggs": {
"publish_state": {
"terms": {
"field": "is_published"
}
}
},
"sort": [ "is_published" ],
"fields": [
{"field": "weight"}
],
"runtime_mappings": {
"weight": {
"type": "long",
"script": "emit(doc['is_published'].value ? 10 : 0)"
}
}
} Параметры для boolean полей
Следующие параметры принимаются полями типа boolean:
| Должно ли поле храниться на диске в столбце, чтобы его можно было использовать для сортировки, агрегаций или скриптов? Принимает значения | |
| Должно ли поле быстро индексироваться? Принимает | |
| Попытка индексирования неправильного типа данных в поле по умолчанию вызывает исключение и отклоняет весь документ. Если этот параметр установлен в значение true, это позволяет игнорировать исключение. Неправильно отформатированное поле не индексируется, но остальные поля в документе обрабатываются нормально. Принимает значения | |
| Принимает любое из перечисленных выше значений true или false. Значение подставляется вместо явных значений | |
| | Определяет, что делать, если скрипт, определенный параметром |
| | Если этот параметр установлен, поле будет индексировать значения, сгенерированные этим скриптом, а не читать значения напрямую из источника. Если для этого поля установлено значение в входном документе, документ будет отклонен с ошибкой. Скрипты имеют тот же формат, что и их эквиваленты runtime. |
| Должно ли значение поля храниться и извлекаться отдельно от поля | |
| Метаданные о поле. | |
| |
(Необязательно, Boolean) Помечает поле как измерение временного ряда. По умолчанию Настройка индекса Поля измерений имеют следующие ограничения:
|
Синтетическое _source
Синтетическое _source доступно только для индексов TSDB (индексы, для которых index.mode установлено в time_series). Для других индексов синтетическое _source находится в техническом предварительном просмотре. Функции в техническом предварительном просмотре могут быть изменены или удалены в будущих выпусках. Elastic будет работать над исправлением любых проблем, но функции в техническом предварительном просмотре не подпадают под SLA поддержки официальных функций GA.
Поля типа boolean поддерживают синтетическое _source в их стандартной конфигурации.
Синтетический источник может сортировать значения поля boolean. Например:
resp = client.indices.create(
index="idx",
settings={
"index": {
"mapping": {
"source": {
"mode": "synthetic"
}
}
}
},
mappings={
"properties": {
"bool": {
"type": "boolean"
}
}
},
)
print(resp)
resp1 = client.index(
index="idx",
id="1",
document={
"bool": [
True,
False,
True,
False
]
},
)
print(resp1) const response = await client.indices.create({
index: "idx",
settings: {
index: {
mapping: {
source: {
mode: "synthetic",
},
},
},
},
mappings: {
properties: {
bool: {
type: "boolean",
},
},
},
});
console.log(response);
const response1 = await client.index({
index: "idx",
id: 1,
document: {
bool: [true, false, true, false],
},
});
console.log(response1); PUT idx
{
"settings": {
"index": {
"mapping": {
"source": {
"mode": "synthetic"
}
}
}
},
"mappings": {
"properties": {
"bool": { "type": "boolean" }
}
}
}
PUT idx/_doc/1
{
"bool": [true, false, true, false]
} Преобразуется в:
{
"bool": [false, false, true, true]
}
© 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/boolean.html