• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3#
4# Copyright 2014 Google Inc. All Rights Reserved.
5
6"""Query with ranked results against the shopping search API"""
7from __future__ import print_function
8
9from googleapiclient.discovery import build
10
11
12SHOPPING_API_VERSION = 'v1'
13DEVELOPER_KEY = 'AIzaSyACZJW4JwcWwz5taR2gjIMNQrtgDLfILPc'
14
15
16def main():
17  """Get and print a histogram of the top 15 brand distribution for a search
18  query.
19
20  Histograms are created by using the "Facets" functionality of the API. A
21  Facet is a view of a certain property of products, containing a number of
22  buckets, one for each value of that property. Or concretely, for a parameter
23  such as "brand" of a product, the facets would include a facet for brand,
24  which would contain a number of buckets, one for each brand returned in the
25  result.
26
27  A bucket contains either a value and a count, or a value and a range. In the
28  simple case of a value and a count for our example of the "brand" property,
29  the value would be the brand name, eg "sony" and the count would be the
30  number of results in the search.
31  """
32  client = build('shopping', SHOPPING_API_VERSION, developerKey=DEVELOPER_KEY)
33  resource = client.products()
34  request = resource.list(source='public', country='US', q=u'digital camera',
35                          facets_include='brand:15', facets_enabled=True)
36  response = request.execute()
37
38  # Pick the first and only facet for this query
39  facet = response['facets'][0]
40
41  print('\n\tHistogram for "%s":\n' % facet['property'])
42
43  labels = []
44  values = []
45
46  for bucket in facet['buckets']:
47    labels.append(bucket['value'].rjust(20))
48    values.append(bucket['count'])
49
50  weighting = 50.0 / max(values)
51
52  for label, value in zip(labels, values):
53    print(label, '#' * int(weighting * value), '(%s)' % value)
54
55  print()
56
57
58if __name__ == '__main__':
59    main()
60