搜尋及套用篩選器

必要的授權範圍

photoslibrary.readonly 範圍允許存取使用者程式庫中的所有媒體項目。

如要搜尋應用程式建立的內容並套用篩選器,就必須使用 photoslibrary.readonly.appcreateddata 範圍。如要進一步瞭解範圍,請參閱「授權範圍」。

可用的篩選器

您可以搜尋使用者應用程式建立的媒體項目庫,找出特定類型的媒體。舉例來說,您可能只想找出某天拍攝的動物相片,或是排除收據相片。您可以為專輯或媒體庫清單套用篩選器,排除或納入特定項目。系統提供五個可用的篩選器,可根據媒體項目屬性篩選:

如果已設定 albumId,請勿在 mediaItems.search 要求中使用篩選器。如果在設定 AlbumId 的情況下使用篩選器,系統會傳回 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,但會移除任何含有 PEOPLE 或為 SELFIES 的媒體項目:

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()]
);

日期和日期範圍

日期篩選器會將傳回結果的日期限制在指定的日期範圍內。有兩種方法可指定日期篩選器:日期篩選器。日期和範圍可以一起使用。系統會傳回符合任何日期或日期範圍的媒體項目。如有需要,您可以修改結果的排序順序

日期

日期包含年、月和日。我們接受以下格式:

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

如果日期的元件為空白或設為零,系統會將其視為萬用字元。舉例來說,如果您只設定日期和月份,而未指定年份,則系統會要求從任何年份的該日期和月份取得項目:

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 動態相片、動態相片、全景相片、全景相片和 VR 相片等特殊相片類型。

影片

VIDEO 可為多種影片格式:

3GP MMV
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
    ]
);