Spec-Zone.ru › Elasticsearch 8
›Elasticsearch Guide [8.17] ›REST APIs

Общие параметры

Все REST API Elasticsearch поддерживают следующие параметры.

Форматированный вывод

При добавлении ?pretty=true к любому запросу, возвращаемый JSON будет отформатирован (используйте только для отладки!). Другой вариант — установить ?format=yaml, что приведёт к возврату результата в (иногда) более читабельном формате YAML.

Вывод в удобочитаемом формате

Статистика возвращается в формате, подходящем для людей (например, "exists_time": "1h" или "size": "1kb") и для компьютеров (например, "exists_time_in_millis": 3600000 или "size_in_bytes": 1024). Удобочитаемые значения можно отключить, добавив ?human=false к строке запроса. Это имеет смысл, когда результаты статистики используются инструментом мониторинга, а не предназначены для просмотра человеком. Значение по умолчанию для флага human — false.

Математика дат

Большинство параметров, которые принимают отформатированное значение даты — такие как gt и lt в range запросах, или from и to в daterange агрегациях — понимают математические операции с датами.

Выражение начинается с базовой даты, которая может быть либо now, либо строкой даты, заканчивающейся на ||. За этой базовой датой может следовать одно или несколько математических выражений:

  • +1h: Добавить один час
  • -1d: Вычесть один день
  • /d: Округлить вниз до ближайшего дня

Поддерживаемые единицы времени отличаются от тех, которые поддерживаются единицами времени для продолжительности. Поддерживаемые единицы:

y

Годы

M

Месяцы

w

Недели

d

Дни

h

Часы

H

Часы

m

Минуты

s

Секунды

Предполагая, что now равно 2001-01-01 12:00:00, некоторые примеры:

now+1h

now в миллисекундах плюс один час. Результат: 2001-01-01 13:00:00

now-1h

now в миллисекундах минус один час. Результат: 2001-01-01 11:00:00

now-1h/d

now в миллисекундах минус один час, округленное вниз до UTC 00:00. Результат: 2001-01-01 00:00:00

2001.02.01\|\|+1M/d

2001-02-01 в миллисекундах плюс один месяц. Результат: 2001-03-01 00:00:00

Фильтрация ответов

Все REST API принимают параметр filter_path, который можно использовать для уменьшения возвращаемого Elasticsearch ответа. Этот параметр принимает список фильтров, разделённых запятыми, выраженных с помощью точечной нотации:

resp = client.search(
    q="kimchy",
    filter_path="took,hits.hits._id,hits.hits._score",
)
print(resp)
response = client.search(
  q: 'kimchy',
  filter_path: 'took,hits.hits._id,hits.hits._score'
)
puts response
const response = await client.search({
  q: "kimchy",
  filter_path: "took,hits.hits._id,hits.hits._score",
});
console.log(response);
GET /_search?q=kimchy&filter_path=took,hits.hits._id,hits.hits._score

Возвращает:

{
  "took" : 3,
  "hits" : {
    "hits" : [
      {
        "_id" : "0",
        "_score" : 1.6375021
      }
    ]
  }
}

Он также поддерживает подстановочный знак * для сопоставления любого поля или части имени поля:

$response = $client->cluster()->state();
resp = client.cluster.state(
    filter_path="metadata.indices.*.stat*",
)
print(resp)
response = client.cluster.state(
  filter_path: 'metadata.indices.*.stat*'
)
puts response
res, err := es.Cluster.State(
	es.Cluster.State.WithFilterPath("metadata.indices.*.stat*"),
)
fmt.Println(res, err)
const response = await client.cluster.state({
  filter_path: "metadata.indices.*.stat*",
});
console.log(response);
GET /_cluster/state?filter_path=metadata.indices.*.stat*

Возвращает:

{
  "metadata" : {
    "indices" : {
      "my-index-000001": {"state": "open"}
    }
  }
}

И подстановочный знак ** может использоваться для включения полей без знания точного пути к полю. Например, мы можем вернуть состояние каждого шарда с помощью этого запроса:

$response = $client->cluster()->state();
resp = client.cluster.state(
    filter_path="routing_table.indices.**.state",
)
print(resp)
response = client.cluster.state(
  filter_path: 'routing_table.indices.**.state'
)
puts response
res, err := es.Cluster.State(
	es.Cluster.State.WithFilterPath("routing_table.indices.**.state"),
)
fmt.Println(res, err)
const response = await client.cluster.state({
  filter_path: "routing_table.indices.**.state",
});
console.log(response);
GET /_cluster/state?filter_path=routing_table.indices.**.state

Возвращает:

{
  "routing_table": {
    "indices": {
      "my-index-000001": {
        "shards": {
          "0": [{"state": "STARTED"}, {"state": "UNASSIGNED"}]
        }
      }
    }
  }
}

Также можно исключить одно или несколько полей, добавив перед фильтром символ -:

$response = $client->count();
resp = client.count(
    filter_path="-_shards",
)
print(resp)
response = client.count(
  filter_path: '-_shards'
)
puts response
res, err := es.Count(
	es.Count.WithFilterPath("-_shards"),
	es.Count.WithPretty(),
)
fmt.Println(res, err)
const response = await client.count({
  filter_path: "-_shards",
});
console.log(response);
GET /_count?filter_path=-_shards

Возвращает:

{
  "count" : 5
}

Для большего контроля включающие и исключающие фильтры можно комбинировать в одном выражении. В этом случае исключающие фильтры будут применены сначала, и результат будет отфильтрован ещё раз с использованием включающих фильтров:

$response = $client->cluster()->state();
resp = client.cluster.state(
    filter_path="metadata.indices.*.state,-metadata.indices.logstash-*",
)
print(resp)
response = client.cluster.state(
  filter_path: 'metadata.indices.*.state,-metadata.indices.logstash-*'
)
puts response
res, err := es.Cluster.State(
	es.Cluster.State.WithFilterPath("metadata.indices.*.state,-metadata.indices.logstash-*"),
)
fmt.Println(res, err)
const response = await client.cluster.state({
  filter_path: "metadata.indices.*.state,-metadata.indices.logstash-*",
});
console.log(response);
GET /_cluster/state?filter_path=metadata.indices.*.state,-metadata.indices.logstash-*

Возвращает:

{
  "metadata" : {
    "indices" : {
      "my-index-000001" : {"state" : "open"},
      "my-index-000002" : {"state" : "open"},
      "my-index-000003" : {"state" : "open"}
    }
  }
}

Обратите внимание, что Elasticsearch иногда возвращает непосредственно необработанное значение поля, например, поле _source. Если вы хотите фильтровать поля _source, вам следует рассмотреть возможность комбинирования уже существующего параметра _source (см. Get API для получения более подробной информации) с параметром filter_path следующим образом:

$params = [
    'index' => 'library',
    'body' => [
        'title' => 'Book #1',
        'rating' => 200.1,
    ],
];
$response = $client->index($params);
$params = [
    'index' => 'library',
    'body' => [
        'title' => 'Book #2',
        'rating' => 1.7,
    ],
];
$response = $client->index($params);
$params = [
    'index' => 'library',
    'body' => [
        'title' => 'Book #3',
        'rating' => 0.1,
    ],
];
$response = $client->index($params);
$response = $client->search();
resp = client.index(
    index="library",
    refresh=True,
    document={
        "title": "Book #1",
        "rating": 200.1
    },
)
print(resp)

resp1 = client.index(
    index="library",
    refresh=True,
    document={
        "title": "Book #2",
        "rating": 1.7
    },
)
print(resp1)

resp2 = client.index(
    index="library",
    refresh=True,
    document={
        "title": "Book #3",
        "rating": 0.1
    },
)
print(resp2)

resp3 = client.search(
    filter_path="hits.hits._source",
    source="title",
    sort="rating:desc",
)
print(resp3)
response = client.index(
  index: 'library',
  refresh: true,
  body: {
    title: 'Book #1',
    rating: 200.1
  }
)
puts response

response = client.index(
  index: 'library',
  refresh: true,
  body: {
    title: 'Book #2',
    rating: 1.7
  }
)
puts response

response = client.index(
  index: 'library',
  refresh: true,
  body: {
    title: 'Book #3',
    rating: 0.1
  }
)
puts response

response = client.search(
  filter_path: 'hits.hits._source',
  _source: 'title',
  sort: 'rating:desc'
)
puts response
{
	res, err := es.Index(
		"library",
		strings.NewReader(`{
	  "title": "Book #1",
	  "rating": 200.1
	}`),
		es.Index.WithRefresh("true"),
		es.Index.WithPretty(),
	)
	fmt.Println(res, err)
}

{
	res, err := es.Index(
		"library",
		strings.NewReader(`{
	  "title": "Book #2",
	  "rating": 1.7
	}`),
		es.Index.WithRefresh("true"),
		es.Index.WithPretty(),
	)
	fmt.Println(res, err)
}

{
	res, err := es.Index(
		"library",
		strings.NewReader(`{
	  "title": "Book #3",
	  "rating": 0.1
	}`),
		es.Index.WithRefresh("true"),
		es.Index.WithPretty(),
	)
	fmt.Println(res, err)
}

{
	res, err := es.Search(
		es.Search.WithSource("title"),
		es.Search.WithFilterPath("hits.hits._source"),
		es.Search.WithSort("rating:desc"),
		es.Search.WithPretty(),
	)
	fmt.Println(res, err)
}
const response = await client.index({
  index: "library",
  refresh: "true",
  document: {
    title: "Book #1",
    rating: 200.1,
  },
});
console.log(response);

const response1 = await client.index({
  index: "library",
  refresh: "true",
  document: {
    title: "Book #2",
    rating: 1.7,
  },
});
console.log(response1);

const response2 = await client.index({
  index: "library",
  refresh: "true",
  document: {
    title: "Book #3",
    rating: 0.1,
  },
});
console.log(response2);

const response3 = await client.search({
  filter_path: "hits.hits._source",
  _source: "title",
  sort: "rating:desc",
});
console.log(response3);
POST /library/_doc?refresh
{"title": "Book #1", "rating": 200.1}
POST /library/_doc?refresh
{"title": "Book #2", "rating": 1.7}
POST /library/_doc?refresh
{"title": "Book #3", "rating": 0.1}
GET /_search?filter_path=hits.hits._source&_source=title&sort=rating:desc
{
  "hits" : {
    "hits" : [ {
      "_source":{"title":"Book #1"}
    }, {
      "_source":{"title":"Book #2"}
    }, {
      "_source":{"title":"Book #3"}
    } ]
  }
}

Уплощенные настройки

Флаг flat_settings влияет на отображение списков настроек. Когда флаг flat_settings имеет значение true, настройки возвращаются в уплощенном формате:

resp = client.indices.get_settings(
    index="my-index-000001",
    flat_settings=True,
)
print(resp)
response = client.indices.get_settings(
  index: 'my-index-000001',
  flat_settings: true
)
puts response
const response = await client.indices.getSettings({
  index: "my-index-000001",
  flat_settings: "true",
});
console.log(response);
GET my-index-000001/_settings?flat_settings=true

Возвращает:

{
  "my-index-000001" : {
    "settings": {
      "index.number_of_replicas": "1",
      "index.number_of_shards": "1",
      "index.creation_date": "1474389951325",
      "index.uuid": "n6gzFZTgS664GUfx0Xrpjw",
      "index.version.created": ...,
      "index.routing.allocation.include._tier_preference" : "data_content",
      "index.provided_name" : "my-index-000001"
    }
  }
}

Когда флаг flat_settings имеет значение false, настройки возвращаются в более удобочитаемом структурированном формате:

resp = client.indices.get_settings(
    index="my-index-000001",
    flat_settings=False,
)
print(resp)
response = client.indices.get_settings(
  index: 'my-index-000001',
  flat_settings: false
)
puts response
const response = await client.indices.getSettings({
  index: "my-index-000001",
  flat_settings: "false",
});
console.log(response);
GET my-index-000001/_settings?flat_settings=false

Возвращает:

{
  "my-index-000001" : {
    "settings" : {
      "index" : {
        "number_of_replicas": "1",
        "number_of_shards": "1",
        "creation_date": "1474389951325",
        "uuid": "n6gzFZTgS664GUfx0Xrpjw",
        "version": {
          "created": ...
        },
        "routing": {
          "allocation": {
            "include": {
              "_tier_preference": "data_content"
            }
          }
        },
        "provided_name" : "my-index-000001"
      }
    }
  }
}

По умолчанию flat_settings установлен в false.

Нечеткое соответствие

Некоторые запросы и API поддерживают параметры для неточного нечеткого сопоставления, используя параметр fuzziness.

При запросе полей text или keyword, fuzziness интерпретируется как Расстояние Левенштейна — количество односимвольных изменений, которые необходимо внести в одну строку, чтобы сделать её идентичной другой строке.

Параметр fuzziness может быть указан как:

0, 1, 2

Максимальное разрешённое расстояние Левенштейна (или количество правок)

AUTO

Генерирует расстояние редактирования на основе длины термина. Низкое и высокое значения расстояния могут быть необязательно предоставлены AUTO:[low],[high]. Если не указаны, по умолчанию используются значения 3 и 6, эквивалентные AUTO:3,6, которые соответствуют длинам:

0..2
Должно совпадать точно
3..5
Разрешена одна правка
>5
Разрешены две правки

AUTO, как правило, является предпочтительным значением для fuzziness.

Включение отладочных следов

По умолчанию, когда запрос возвращает ошибку, Elasticsearch не включает отладочные следы ошибки. Вы можете включить это поведение, установив параметр URL error_trace в значение true. Например, по умолчанию, когда вы отправляете некорректный параметр size в API _search:

resp = client.search(
    index="my-index-000001",
    size="surprise_me",
)
print(resp)
const response = await client.search({
  index: "my-index-000001",
  size: "surprise_me",
});
console.log(response);
POST /my-index-000001/_search?size=surprise_me

Ответ выглядит следующим образом:

{
  "error" : {
    "root_cause" : [
      {
        "type" : "illegal_argument_exception",
        "reason" : "Failed to parse int parameter [size] with value [surprise_me]"
      }
    ],
    "type" : "illegal_argument_exception",
    "reason" : "Failed to parse int parameter [size] with value [surprise_me]",
    "caused_by" : {
      "type" : "number_format_exception",
      "reason" : "For input string: \"surprise_me\""
    }
  },
  "status" : 400
}

Но если вы установите error_trace=true:

resp = client.search(
    index="my-index-000001",
    size="surprise_me",
    error_trace=True,
)
print(resp)
const response = await client.search({
  index: "my-index-000001",
  size: "surprise_me",
  error_trace: "true",
});
console.log(response);
POST /my-index-000001/_search?size=surprise_me&error_trace=true

Ответ выглядит так:

{
  "error": {
    "root_cause": [
      {
        "type": "illegal_argument_exception",
        "reason": "Failed to parse int parameter [size] with value [surprise_me]",
        "stack_trace": "Failed to parse int parameter [size] with value [surprise_me]]; nested: IllegalArgumentException..."
      }
    ],
    "type": "illegal_argument_exception",
    "reason": "Failed to parse int parameter [size] with value [surprise_me]",
    "stack_trace": "java.lang.IllegalArgumentException: Failed to parse int parameter [size] with value [surprise_me]\n    at org.elasticsearch.rest.RestRequest.paramAsInt(RestRequest.java:175)...",
    "caused_by": {
      "type": "number_format_exception",
      "reason": "For input string: \"surprise_me\"",
      "stack_trace": "java.lang.NumberFormatException: For input string: \"surprise_me\"\n    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)..."
    }
  },
  "status": 400
}

© 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/common-options.html

Spec-Zone.ru

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