Выберите поля для возврата

Разработчики из Европейской экономической зоны (ЕЭЗ)

Введение

When you call the Place Details (New) , Nearby Search (New) , or Text Search (New) methods, you must specify which fields you want returned in the response. There is no default list of returned fields. If you omit this list, the methods return an error.

Полный список поддерживаемых полей данных и соответствующих им артикулов можно найти в разделе «Размещение полей данных (новое)» . Информацию о полях, специфичных для каждого API, см. ниже:

You specify the field list by creating a response field mask . You then pass the response field mask to either method by using the parameter $fields or fields , or by using the HTTP or gRPC header X-Goog-FieldMask .

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

Define a response field mask

The response field mask is a comma-separated list of paths, where each path specifies a unique field in the response body. The path starts from the top-level response message and uses a dot-separated path to the specified field.

Создайте путь к полю следующим образом:

topLevelField[.secondLevelField][.thirdLevelField][...]

Вы можете запросить все поля, используя маску поля * .

Для получения дополнительной информации о том, как создавать маски полей, см. файл field_mask.proto .

Определите, какие маски полей следует использовать.

Вот как можно определить, какие маски полей вы хотите использовать:

  1. Request all fields using a field mask of * .
  2. Изучите иерархию полей в ответе и определите, какие поля вам нужны.
  3. Build your field mask using the field hierarchy.

Поиск поблизости (новый) и текстовый поиск (новый) возвращают массив объектов Place в поле places ответа. Для этих API places является полем верхнего уровня ответа.

Например, чтобы увидеть полный объект ответа при текстовом поиске (новая функция):

curl -X POST -d '{
  "textQuery" : "Spicy Vegetarian Food in Sydney, Australia"
}' \
-H 'Content-Type: application/json' -H 'X-Goog-Api-Key: API_KEY' \
-H 'X-Goog-FieldMask: *' \
'https://places.googleapis.com/v1/places:searchText'

Полный ответ на запрос текстового поиска (новый) имеет следующий вид:

{
  "places": [
    {
      "name": "places/ChIJs5ydyTiuEmsR0fRSlU0C7k0",
      "id": "ChIJs5ydyTiuEmsR0fRSlU0C7k0",
      "types": [
        "vegetarian_restaurant",
        "vegan_restaurant",
        "meal_takeaway",
        "restaurant",
        "food",
        "point_of_interest",
        "establishment"
      ],
      "nationalPhoneNumber": "0433 479 794",
      "internationalPhoneNumber": "+61 433 479 794",
      "formattedAddress": "29 King St, Sydney NSW 2000, Australia",
      "displayName": {
        "text": "Spiced @ Barangaroo",
        "languageCode": "en"
      },      ...
    },
  ...
  ]
}

Таким образом, для этих API-интерфейсов вы указываете маску поля в следующем формате:

places[.secondLevelField][.thirdLevelField][...]

If you want to return only the formattedAddress and displayName fields, set your field mask to:

places.formattedAddress,places.displayName

Specifying displayName includes both the text and language fields of displayName . If you only want the text field, set the field mask as:

places.formattedAddress,places.displayName.text

Определите маску поля ответа для сведений о месте (новая функция).

Функция «Подробная информация о месте» (новая) возвращает один объект Place в следующем формате:

{
  "name": "places/ChIJkR8FdQNB0VQRm64T_lv1g1g",
  "id": "ChIJkR8FdQNB0VQRm64T_lv1g1g",
  "types": [
    "locality",
    "political"
  ],
  "formattedAddress": "Trinidad, CA 95570, USA",
  "displayName": {
    "text": "Trinidad",
    "languageCode": "en"
  }
  ...
}

Таким образом, для этого API вы указываете маску поля, перечислив поля объекта Place, которые хотите вернуть:

curl -X GET -H 'Content-Type: application/json' \
-H "X-Goog-Api-Key: API_KEY" \
-H "X-Goog-FieldMask: formattedAddress,displayName" \
https://places.googleapis.com/v1/places/ChIJj61dQgK6j4AR4GeTYWZsKWw

вызов gRPC

Для gRPC установите переменную, содержащую маску поля ответа. Затем вы можете передать эту переменную в запрос.

const (
  fieldMask = "places.formattedAddress,places.displayName"
)

Field path considerations

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

  • Сокращает время обработки , поэтому результаты возвращаются с меньшей задержкой.
  • Ensures stable latency performance if the API adds more response fields in the future, and those new fields require extra computation time. If you select all fields, or if you select all fields at the top level, you might experience performance degradation when all new fields are automatically included in your response.
  • Это приводит к уменьшению размера ответа , что, в свою очередь, увеличивает пропускную способность сети.
  • Это гарантирует, что вы не запрашиваете ненужные данные , что помогает избежать лишнего времени обработки и дополнительных расходов.