搜索和应用过滤条件

所需的授权范围

photoslibrary.readonly 范围允许访问用户媒体库中的所有媒体内容。

若要搜索应用创建的内容并对其应用过滤条件,需要 photoslibrary.readonly.appcreateddata 范围。如需详细了解范围,请参阅授权范围

可用过滤器

您可以在用户的应用创建的媒体内容库中搜索特定类型的媒体。例如,您可能只想查找特定日期的动物相关内容,或者可能想要排除收据照片。您可以在影集或媒体库列表中应用过滤器,从而排除或添加特定内容。根据媒体内容属性,提供以下五种可用的过滤器:

如果已设置 albumId,则不应在 mediaItems.search 请求中使用过滤器。如果在已设置 photosId 时使用过滤条件,系统会返回 INVALID_ARGUMENT 错误 (400)。

结果会按媒体内容创建时间排序。对于使用日期过滤条件的查询,可以修改排序顺序

新上传的媒体需过一段时间后才能出现在搜索结果中,媒体会立即显示在未经过滤的搜索结果中。

若媒体内容的日期是未来日期,则其不会出现在已过滤的搜索结果中。但会出现在未经过滤的搜索结果以及影集搜索结果中。

应用过滤器

如需应用过滤器,请调用 mediaItems.search 并指定 filter 属性。

REST

以下是 POST 请求:

POST https://photoslibrary.googleapis.com/v1/mediaItems:search
Content-type: application/json
Authorization: Bearer oauth2-token
{
  "pageSize": "100",
  "filters": {
    ...
  }
}

POST 请求会返回以下响应:

{
  "mediaItems": [
    ...
  ],
  "nextPageToken": "token-for-pagination"
}

Java

try {
  // Create a new Filter object
  Filters filters = Filters.newBuilder()
      // .setContentFilter(...)
      // .setDateFilter(...)
      // ...
      .build();

  // Specify the Filter object in the searchMediaItems call
  SearchMediaItemsPagedResponse response = photosLibraryClient.searchMediaItems(filters);
  for (MediaItem item : response.iterateAll()) {
    // ...
  }
} catch (ApiException e) {
  // Handle error
}

PHP

try {
    $filtersBuilder = new FiltersBuilder();
    // $filtersBuilder->addIncludedCategory(...);
    // $filtersBuilder->addDate(...);
    // ...
    // Make a search call with the options set in the filters builder
    $response = $photosLibraryClient->searchMediaItems(
        ['filters' => $filtersBuilder->build()]
    );
    foreach ($response->iterateAllElements() as $element) {
        // ...
    }
} catch (\Google\ApiCore\ApiException $e) {
    // Handle error
}

有关详情,请参阅列出媒体库内容、影集和媒体内容

内容分类

您需处理所有媒体内容并为其分配标签。您可以添加和排除以下任何类别。

ANIMALS FASHION LANDMARKS RECEIPTS WEDDINGS
ARTS FLOWERS LANDSCAPES SCREENSHOTS WHITEBOARDS
BIRTHDAYS FOOD NIGHT SELFIES  
CITYSCAPES GARDENS PEOPLE SPORT  
CRAFTS HOLIDAYS PERFORMANCES TRAVEL  
DOCUMENTS HOUSES PETS UTILITY  

实用助手照片涵盖大量媒体内容。此类别通常包含用户为执行某项任务而捕获的内容,且完成该任务后可能就不再需要这些内容,其中包括文档、收据、屏幕截图、便笺、菜单及其他类似的媒体内容。

这些类别的准确性仅与 Google 相册内的同等标签相同。有时,项的标签可能有误,因此,我们不保证内容类别过滤器的准确性。

添加类别

如果您添加多个类别,则返回结果会包含与任一类别匹配的媒体内容。每个请求最多可包含 10 个类别。 以下示例过滤器将返回 LANDSCAPESLANDMARKS 类别的所有内容。

REST

{
  "filters": {
    "contentFilter": {
      "includedContentCategories": [
        "LANDSCAPES",
        "LANDMARKS"
      ]
    }
  }
}

Java

// Create a content filter that includes landmarks and landscapes
ContentFilter contentFilter = ContentFilter.newBuilder()
    .addIncludedContentCategories(ContentCategory.LANDMARKS)
    .addIncludedContentCategories(ContentCategory.LANDSCAPES)
    .build();
// Create a new Filters object
Filters filters = Filters.newBuilder()
    .setContentFilter(contentFilter)
    .build();
// Specify the Filter object in the searchMediaItems call
SearchMediaItemsPagedResponse response = photosLibraryClient.searchMediaItems(filters);

PHP

// Create a content filter that includes landmarks and landscapes
$filtersBuilder = new FiltersBuilder();
$filtersBuilder->addIncludedCategory(ContentCategory::LANDMARKS);
$filtersBuilder->addIncludedCategory(ContentCategory::LANDSCAPES);
// Make a search call with the options set in the filters builder
$response = $photosLibraryClient->searchMediaItems(
    ['filters' => $filtersBuilder->build()]
);

排除类别

返回结果仅显示与任一已排除类别不匹配的媒体内容。 与添加的类别类似,每个请求最多可排除 10 个类别。

以下过滤器将返回不属于 PEOPLESELFIES 类别的所有内容:

REST

{
  "filters": {
    "contentFilter": {
      "excludedContentCategories": [
        "PEOPLE",
        "SELFIES"
      ]
    }
  }
}

Java

// Create a content filter that excludes people and selfies
ContentFilter contentFilter = ContentFilter.newBuilder()
    .addExcludedContentCategories(ContentCategory.PEOPLE)
    .addExcludedContentCategories(ContentCategory.SELFIES)
    .build();
// Create a new Filters object
Filters filters = Filters.newBuilder()
    .setContentFilter(contentFilter)
    .build();
// Specify the Filter object in the searchMediaItems call
SearchMediaItemsPagedResponse response = photosLibraryClient.searchMediaItems(filters);

PHP

// Create a content filter that excludes people and selfies
$filtersBuilder = new FiltersBuilder();
$filtersBuilder->addExcludedCategory(ContentCategory::PEOPLE);
$filtersBuilder->addExcludedCategory(ContentCategory::SELFIES);
// Make a search call with the options set in the filters builder
$response = $photosLibraryClient->searchMediaItems(
    ['filters' => $filtersBuilder->build()]
);

添加和排除多个类别

您可以添加一些类别并排除其他类别。以下示例会返回 LANDSCAPESLANDMARKS,但会移除包含 PEOPLESELFIES 的所有媒体内容:

REST

{
  "filters": {
    "contentFilter": {
      "includedContentCategories": [
        "LANDSCAPES",
        "LANDMARKS"
      ],
      "excludedContentCategories": [
        "PEOPLE",
        "SELFIES"
      ]
    }
  }
}

Java

// Create a content filter that excludes people and selfies and includes landmarks and landscapes
ContentFilter contentFilter = ContentFilter.newBuilder()
    .addIncludedContentCategories(ContentCategory.LANDSCAPES)
    .addIncludedContentCategories(ContentCategory.LANDMARKS)
    .addExcludedContentCategories(ContentCategory.PEOPLE)
    .addExcludedContentCategories(ContentCategory.SELFIES)
    .build();
// Create a new Filters object
Filters filters = Filters.newBuilder()
    .setContentFilter(contentFilter)
    .build();
// Specify the Filters object in the searchMediaItems call
SearchMediaItemsPagedResponse response = photosLibraryClient.searchMediaItems(filters);

PHP

// Create a content filter that excludes people and selfies and includes landmarks and landscapes
$filtersBuilder = new FiltersBuilder();
$filtersBuilder->addIncludedCategory(ContentCategory::LANDMARKS);
$filtersBuilder->addIncludedCategory(ContentCategory::LANDSCAPES);
$filtersBuilder->addExcludedCategory(ContentCategory::PEOPLE);
$filtersBuilder->addExcludedCategory(ContentCategory::SELFIES);
// Make a search call with the options set in the filters builder
$response = $photosLibraryClient->searchMediaItems(
    ['filters' => $filtersBuilder->build()]
);

日期和日期范围

日期过滤器可将返回结果的日期限制为指定的日期范围。有两种方法可指定日期过滤器:指定日期或指定日期范围。日期和范围可以一起使用。系统会返回与任意日期或日期范围匹配的媒体内容。(可选)您可以修改结果的排序顺序

日期

包含年、月和日的日期。以下为可接受的格式:

  • 年,月
  • 年,月,日
  • 月,日

如果日期的某个部分为空或设为 0,则将其视为通配符。例如,如果设置日和月,而未设置年,则您请求的是任一年该月该日的内容:

REST

{
  "filters": {
    "dateFilter": {
      "dates": [
        {
          "month": 2,
          "day": 15
        }
      ]
    }
  }
}

Java

// Create a new com.google.type.Date object using a builder
// Note that there are different valid combinations as described above
Date dayFebruary15 = Date.newBuilder()
    .setDay(15)
    .setMonth(2)
    .build();
// Create a new dateFilter. You can also set multiple dates here
DateFilter dateFilter = DateFilter.newBuilder()
    .addDates(dayFebruary15)
    .build();
// Create a new Filters object
Filters filters = Filters.newBuilder()
    .setDateFilter(dateFilter)
    .build();
// Specify the Filters object in the searchMediaItems call
SearchMediaItemsPagedResponse response = photosLibraryClient.searchMediaItems(filters);

PHP

// Create a new Google\Type\Date object with a day and a month
// Note that there are different valid combinations as described above
$dateFebruary15 = new Date();
$dateFebruary15->setDay(15);
$dateFebruary15->setMonth(2);
$filtersBuilder = new FiltersBuilder();
// Add the date to the filter. You can also set multiple dates here
$filtersBuilder->addDate($dateFebruary15);
// Make a search call with the options set in the filters builder
$response = $photosLibraryClient->searchMediaItems(
    ['filters' => $filtersBuilder->build()]
);

日期范围

日期范围比日期更加灵活。例如,您可以使用日期范围查看某个月的一组日期。

日期范围包含 startDateendDate,且必须同时设置二者。如日期中所述,日期范围内的每个日期均具有相同的格式限制。这些日期必须具有相同的格式:如果开始日期包含年和月,则结束日期也必须包含年和月。此限制适用于所应用过滤器中的整个日期范围,包括开始日期和结束日期:

REST

{
  "filters": {
    "dateFilter": {
      "ranges": [
        {
          "startDate": {
            "year": 2014,
            "month": 6,
            "day": 12
          },
          "endDate": {
            "year": 2014,
            "month": 7,
            "day": 13
          }
        }
      ]
    }
  }
}

Java

// Create new com.google.type.Date objects for two dates
Date day2014June12 = Date.newBuilder()
    .setDay(12)
    .setMonth(6)
    .setYear(2014)
    .build();
Date day2014July13 = Date.newBuilder()
    .setDay(13)
    .setMonth(7)
    .setYear(2014)
    .build();
// Create a DateRange from these two dates
DateRange dateRange = DateRange.newBuilder()
    .setStartDate(day2014June12)
    .setEndDate(day2014July13)
    .build();
// Create a new dateFilter with the date range. You can also set multiple date ranges here
DateFilter dateFilter = DateFilter.newBuilder()
    .addRanges(dateRange)
    .build();
// Create a new Filters object
Filters filters = Filters.newBuilder()
    .setDateFilter(dateFilter)
    .build();
// Specify the Filters object in the searchMediaItems call
SearchMediaItemsPagedResponse response = photosLibraryClient.searchMediaItems(filters);

PHP

// Create two new Google\Type\Date objects
    $date2014June12 = new Date();
    $date2014June12->setDay(12);
    $date2014June12->setMonth(6);
    $date2014June12->setYear(2014);

    $date2014July13 = new Date();
    $date2014July13->setDay(13);
    $date2014July13->setMonth(7);
    $date2014July13->setYear(2014);

    // Add the two dates as a date range to the filter
    // You can also set multiple date ranges here
    $filtersBuilder = new FiltersBuilder();
    $filtersBuilder->addDateRange($date2014June12, $date2014July13);

    // Make a search call with the options set in the filters builder
    $response = $photosLibraryClient->searchMediaItems(
        ['filters' => $filtersBuilder->build()]
    );

组合日期和日期范围

您可以同时使用多个日期和日期范围,结果中将包含这些日期内的所有内容。单独的日期和日期范围不需要采用相同的格式,但各个范围的开始日期和结束日期需要遵循:

REST

{
  "filters": {
    "dateFilter": {
      "dates": [
        {
          "year": 2013
        },
        {
          "year": 2011,
          "month": 11
        }
      ],
      "ranges": [
        {
          "startDate": {
            "month": 1
          },
          "endDate": {
            "month": 3
          }
        },
        {
          "startDate": {
            "month": 3,
            "day": 24
          },
          "endDate": {
            "month": 5,
            "day": 2
          }
        }
      ]
    }
  }
}

Java

// Create a new com.google.type.Date object for the year 2013
Date day2013 = Date.newBuilder()
    .setYear(2013)
    .build();
// Create a new com.google.type.Date object for November 2011
Date day2011November = Date.newBuilder()
    .setMonth(11)
    .setYear(2011)
    .build();
// Create a date range for January to March
DateRange dateRangeJanuaryToMarch = DateRange.newBuilder()
    .setStartDate(Date.newBuilder().setMonth(1).build())
    .setEndDate(Date.newBuilder().setMonth(3).build())
    .build();
// Create a date range for March 24 to May 2
DateRange dateRangeMarch24toMay2 = DateRange.newBuilder()
    .setStartDate(Date.newBuilder().setMonth(3).setDay(24).build())
    .setEndDate(Date.newBuilder().setMonth(5).setDay(2).build())
    .build();
// Create a new dateFilter with the dates and date ranges
DateFilter dateFilter = DateFilter.newBuilder()
    .addDates(day2013)
    .addDates(day2011November)
    .addRanges(dateRangeJanuaryToMarch)
    .addRanges(dateRangeMarch24toMay2)
    .build();
// Create a new Filters object
Filters filters = Filters.newBuilder()
    .setDateFilter(dateFilter)
    .build();
// Specify the Filter object in the searchMediaItems call
SearchMediaItemsPagedResponse response = photosLibraryClient.searchMediaItems(filters);

PHP

// Create a new Google\Type\Date object for the year 2013
$date2013 = new Date();
$date2013->setYear(2013);

// Create a new Google\Type\Date object for November 2011
$dateNovember2011 = new Date();
$dateNovember2011->setMonth(11);
$dateNovember2011->setYear(2011);

$filtersBuilder = new FiltersBuilder();

// Create a date range for January to March
$filtersBuilder->addDateRange((new Date())->setMonth(1),
    (new Date())->setMonth(3));

// Create a date range for March 24 to May 2
$filtersBuilder->addDateRange((new Date())->setMonth(3)->setDay(24),
    (new Date())->setMonth(5)->setDay(2));

$filtersBuilder->addDate($date2013);
$filtersBuilder->addDate($dateNovember2011);

// Make a search call with the options set in the filters builder
$response = $photosLibraryClient->searchMediaItems(
    ['filters' => $filtersBuilder->build()]
);

媒体内容功能

功能过滤条件将结果限制为具有特定特征的内容,例如已在 Google 相册应用中标记为收藏夹的内容。

收藏

FeatureFilter 中添加 FAVORITES 项功能,以便仅返回由用户标记为收藏的媒体内容:

REST

{
  "filters" : {
    "featureFilter": {
      "includedFeatures": [
        "FAVORITES"
      ]
    }
  }
}

Java

// Create a new FeatureFilter for favorite media items
FeatureFilter featureFilter = FeatureFilter.newBuilder()
    .addIncludedFeatures(Feature.FAVORITES)
    .build();
// Create a new Filters object
Filters filters = Filters.newBuilder()
    .setFeatureFilter(featureFilter)
    .build();
// Specify the Filters object in the searchMediaItems call
SearchMediaItemsPagedResponse response = photosLibraryClient.searchMediaItems(filters);

PHP

// Create a new FeatureFilter for favorite media items
$filtersBuilder = new FiltersBuilder();
$filtersBuilder->addIncludedFeature(Feature::FAVORITES);

// Make a search call with the options set in the filters builder
$response = $photosLibraryClient->searchMediaItems(
    ['filters' => $filtersBuilder->build()]
);

媒体类型

您可以将结果的媒体类型限制为照片视频

照片

PHOTO 可以为以下任一图片格式:

BMP JPG
GIF PNG
HEIC TIFF
ICO WEBP

它还包括特殊照片类型,例如 iOS Live Photo、动态照片、全景图片、Photo Sphere 照片和 VR 照片。

视频

VIDEO 可以是多种视频格式:

3GP 综合格斗
3G2 MOD
ASF MOV
AVI MP4
DIVX MPG
M2T MTS
M2TS TOD
M4V WMV
MKV  

VIDEO 还包括如下特殊视频格式:VR 视频、慢镜头视频以及在 Google 相册应用中创建的动画。

以下示例按 PHOTO 进行过滤:

REST

{
  "filters": {
    "mediaTypeFilter": {
      "mediaTypes": [
        "PHOTO"
      ]
    }
  }
}

Java

// Create a new MediaTypeFilter for Photo media items
MediaTypeFilter mediaType = MediaTypeFilter.newBuilder()
    .addMediaTypes(MediaType.PHOTO)
    .build();
// Create a new Filters object
Filters filters = Filters.newBuilder()
    .setMediaTypeFilter(mediaType)
    .build();
// Specify the Filters object in the searchMediaItems call
SearchMediaItemsPagedResponse response = photosLibraryClient.searchMediaItems(filters);

PHP

// Create a new MediaTypeFilter for Photo media items
$filtersBuilder = new FiltersBuilder();
$filtersBuilder->setMediaType(MediaType::PHOTO);

// Make a search call with the options set in the filters builder
$response = $photosLibraryClient->searchMediaItems(
    ['filters' => $filtersBuilder->build()]
);

您无法组合使用多种媒体类型的过滤器。

已归档状态

您的用户可能已将部分照片归档。默认情况下,搜索结果中不会返回已归档的照片。如需包含已归档的内容,您可以在过滤条件中设置标志,如以下示例所示:

REST

{
  "filters": {
    "includeArchivedMedia": true
  }
}

Java

// Create a new Filters object that includes archived media
Filters filters = Filters.newBuilder()
    .setIncludeArchivedMedia(true)
    .build();

// Specify the Filters object in the searchMediaItems call
SearchMediaItemsPagedResponse response = photosLibraryClient.searchMediaItems(filters);

PHP

// Create a new Filters object that includes archived media
$filtersBuilder = new FiltersBuilder();
$filtersBuilder->setIncludeArchivedMedia(true);

// Make a search call with the options set in the filters builder
$response = $photosLibraryClient->searchMediaItems(
    ['filters' => $filtersBuilder->build()]
);

组合过滤器

不同种类的过滤器可以相互组合。系统只会返回与所有请求的功能匹配的内容。

组合过滤器时,每种过滤器类型的格式限制与单独使用时的格式限制相同。在以下示例中,仅返回已归类为 SPORT 且日期为 2014 年或 2010 年的照片:

REST

{
  "filters": {
    "contentFilter": {
      "includedContentCategories": [
        "SPORT"
      ]
    },
    "dateFilter": {
      "dates": [
        {
          "year": 2014
        },
        {
          "year": 2010
        }
      ]
    },
    "mediaTypeFilter": {
      "mediaTypes": [
        "PHOTO"
      ]
    }
  }
}

Java

// Create a new ContentFilter that only includes SPORT items
ContentFilter contentFilter = ContentFilter.newBuilder()
    .addIncludedContentCategories(ContentCategory.SPORT)
    .build();
// Create a new media type filter that only includes PHOTO media items
MediaTypeFilter mediaTypeFilter = MediaTypeFilter.newBuilder()
    .addMediaTypes(MediaType.PHOTO)
    .build();
// Create a new DateFilter that only includes items from 2010 or 2014
Date year2014 = Date.newBuilder().setYear(2014).build();
Date year2010 = Date.newBuilder().setYear(2010).build();
DateFilter dateFilter = DateFilter.newBuilder()
    .addDates(year2010)
    .addDates(year2014)
    .build();
// Create a new Filters object combining these filters
Filters filters = Filters.newBuilder()
    .setDateFilter(dateFilter)
    .setMediaTypeFilter(mediaTypeFilter)
    .setContentFilter(contentFilter)
    .build();
// Specify the Filter object in the searchMediaItems call
SearchMediaItemsPagedResponse response = photosLibraryClient.searchMediaItems(filters);

PHP

// Create a new ContentFilter
$filtersBuilder = new FiltersBuilder();
// Only include SPORT items
$filtersBuilder->addIncludedCategory(ContentCategory::SPORT);
// Only include PHOTO media items
$filtersBuilder->setMediaType(MediaType::PHOTO);
// Only include items from 2010 or 2014
$year2014 = new Date();
$year2014->setYear(2014);
$year2010 = new Date();
$year2010->setYear(2010);
$filtersBuilder->addDateRange($year2010, $year2014);

// Make a search call with the options set in the filters builder
// Filters have been combined in the filter builder
$response = $photosLibraryClient->searchMediaItems(
    ['filters' => $filtersBuilder->build()]
);

对结果进行排序

只有使用日期过滤条件的查询才能排序。

如果您未指定排序选项,则结果将按降序排序(最新的结果排在前面)。

下表显示了 orderBy 参数支持的选项:

orderBy 参数
MediaMetadata.creation_time desc 按降序(最新项优先)返回媒体项
MediaMetadata.creation_time 按升序返回媒体项(最早的内容排在最前面)

以下示例会返回 2017 年的所有媒体内容,并按最早到最新的时间顺序显示。

REST

{
  "filters": {
    "dateFilter": {
      "dates": [
        {
          "year": 2017
        }
      ]
    }
  },
  "orderBy": "MediaMetadata.creation_time"
}

Java

// Create a new dateFilter for the year 2017.
DateFilter dateFilter = DateFilter.newBuilder()
        .addDates(Date.newBuilder().setYear(2017))
        .build();

// Create a new Filters object
Filters filters = Filters.newBuilder()
        .setDateFilter(dateFilter)
        .build();

// Sort results by oldest item first.
final OrderBy newestFirstOrder = OrderBy.MEDIAMETADATA_CREATION_TIME;

// Specify the filter and sort order in the searchMediaItems call.
SearchMediaItemsPagedResponse response
        = photosLibraryClient.searchMediaItems(filters, newestFirstOrder);

PHP

// Create a new dateFilter for the year 2017.
$filtersBuilder = new FiltersBuilder();
$filtersBuilder->addDate((new Date())->setYear(2017));

// Make a search call with the options set in the filters builder and sort
// the results by oldest item first.
$response = $photosLibraryClient->searchMediaItems(
    [
        'filters' => $filtersBuilder->build(),
        'orderBy' => OrderBy::MEDIAMETADATA_CREATION_TIME
    ]
);