Spec-Zone.ru › Elasticsearch 8
›Elasticsearch Guide [8.17] ›Отображение ›Типы данных полей

Тип поля boolean

Поля типа boolean принимают JSON true и false значения, но также могут принимать строки, которые интерпретируются как true или false:

Ложные значения

false, "false", "" (пустая строка)

Истинные значения

true, "true"

Например:

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 
    }
  }
}

Индексирование документа с "true", которое интерпретируется как true.

Поиск документов со значением JSON true.

Агрегации, такие как 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:

doc_values

Должно ли поле храниться на диске в столбце, чтобы его можно было использовать для сортировки, агрегаций или скриптов? Принимает значения true (по умолчанию) или false.

index

Должно ли поле быстро индексироваться? Принимает true (по умолчанию) и false. Поля, для которых включен только doc_values, все еще могут быть запрошены с помощью запросов на основе термов или диапазонов, но медленнее.

ignore_malformed

Попытка индексирования неправильного типа данных в поле по умолчанию вызывает исключение и отклоняет весь документ. Если этот параметр установлен в значение true, это позволяет игнорировать исключение. Неправильно отформатированное поле не индексируется, но остальные поля в документе обрабатываются нормально. Принимает значения true или false. Обратите внимание, что это нельзя установить, если используется параметр script.

null_value

Принимает любое из перечисленных выше значений true или false. Значение подставляется вместо явных значений null. По умолчанию null, что означает, что поле считается отсутствующим. Обратите внимание, что это нельзя установить, если используется параметр script.

on_script_error

Определяет, что делать, если скрипт, определенный параметром script, выбросит ошибку во время индексирования. Принимает значения fail (по умолчанию), что приведет к отклонению всего документа, и continue, которое зарегистрирует поле в метаданных документа _ignored и продолжит индексирование. Этот параметр может быть установлен только если установлен параметр script.

script

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

store

Должно ли значение поля храниться и извлекаться отдельно от поля _source. Принимает значения true или false (по умолчанию).

meta

Метаданные о поле.

time_series_dimension

(Необязательно, Boolean)

Помечает поле как измерение временного ряда. По умолчанию false.

Настройка индекса index.mapping.dimension_fields.limit ограничивает количество измерений в индексе.

Поля измерений имеют следующие ограничения:

  • Параметры отображения doc_values и index должны быть true.

Синтетическое _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

Spec-Zone.ru

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