forked from GoogleCloudPlatform/python-docs-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsnippets.py
More file actions
287 lines (216 loc) · 9.04 KB
/
Copy pathsnippets.py
File metadata and controls
287 lines (216 loc) · 9.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
# Copyright 2016 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from datetime import datetime
from google.appengine.api import search
def simple_search(index):
index.search('rose water')
def search_date(index):
index.search('1776-07-04')
def search_terms(index):
# search for documents with pianos that cost less than $5000
index.search("product = piano AND price < 5000")
def create_document():
document = search.Document(
# Setting the doc_id is optional. If omitted, the search service will
# create an identifier.
doc_id='PA6-5000',
fields=[
search.TextField(name='customer', value='Joe Jackson'),
search.HtmlField(
name='comment', value='this is <em>marked up</em> text'),
search.NumberField(name='number_of_visits', value=7),
search.DateField(name='last_visit', value=datetime.now()),
search.DateField(
name='birthday', value=datetime(year=1960, month=6, day=19)),
search.GeoField(
name='home_location', value=search.GeoPoint(37.619, -122.37))
])
return document
def add_document_to_index(document):
index = search.Index('products')
index.put(document)
def add_document_and_get_doc_id(documents):
index = search.Index('products')
results = index.put(documents)
document_ids = [document.id for document in results]
return document_ids
def get_document_by_id():
index = search.Index('products')
# Get a single document by ID.
document = index.get("AZ125")
# Get a range of documents starting with a given ID.
documents = index.get_range(start_id="AZ125", limit=100)
return document, documents
def query_index():
index = search.Index('products')
query_string = 'product: piano AND price < 5000'
results = index.search(query_string)
for scored_document in results:
print(scored_document)
def delete_all_in_index(index):
# index.get_range by returns up to 100 documents at a time, so we must
# loop until we've deleted all items.
while True:
# Use ids_only to get the list of document IDs in the index without
# the overhead of getting the entire document.
document_ids = [
document.doc_id
for document
in index.get_range(ids_only=True)]
# If no IDs were returned, we've deleted everything.
if not document_ids:
break
# Delete the documents for the given IDs
index.delete(document_ids)
def async_query(index):
futures = [index.search_async('foo'), index.search_async('bar')]
results = [future.get_result() for future in futures]
return results
def query_options():
index = search.Index('products')
query_string = "product: piano AND price < 5000"
# Create sort options to sort on price and brand.
sort_price = search.SortExpression(
expression='price',
direction=search.SortExpression.DESCENDING,
default_value=0)
sort_brand = search.SortExpression(
expression='brand',
direction=search.SortExpression.DESCENDING,
default_value="")
sort_options = search.SortOptions(expressions=[sort_price, sort_brand])
# Create field expressions to add new fields to the scored documents.
price_per_note_expression = search.FieldExpression(
name='price_per_note', expression='price/88')
ivory_expression = search.FieldExpression(
name='ivory', expression='snippet("ivory", summary, 120)')
# Create query options using the sort options and expressions created
# above.
query_options = search.QueryOptions(
limit=25,
returned_fields=['model', 'price', 'description'],
returned_expressions=[price_per_note_expression, ivory_expression],
sort_options=sort_options)
# Build the Query and run the search
query = search.Query(query_string=query_string, options=query_options)
results = index.search(query)
for scored_document in results:
print(scored_document)
def query_results(index, query_string):
result = index.search(query_string)
total_matches = result.number_found
list_of_docs = result.results
number_of_docs_returned = len(list_of_docs)
return total_matches, list_of_docs, number_of_docs_returned
def query_offset(index, query_string):
offset = 0
while True:
# Build the query using the current offset.
options = search.QueryOptions(offset=offset)
query = search.Query(query_string=query_string, options=options)
# Get the results
results = index.search(query)
number_retrieved = len(results.results)
if number_retrieved == 0:
break
# Add the number of documents found to the offset, so that the next
# iteration will grab the next page of documents.
offset += number_retrieved
# Process the matched documents
for document in results:
print(document)
def query_cursor(index, query_string):
cursor = search.Cursor()
while cursor:
# Build the query using the cursor.
options = search.QueryOptions(cursor=cursor)
query = search.Query(query_string=query_string, options=options)
# Get the results and the next cursor
results = index.search(query)
cursor = results.cursor
for document in results:
print(document)
def query_per_document_cursor(index, query_string):
cursor = search.Cursor(per_result=True)
# Build the query using the cursor.
options = search.QueryOptions(cursor=cursor)
query = search.Query(query_string=query_string, options=options)
# Get the results.
results = index.search(query)
document_cursor = None
for document in results:
# discover some document of interest and grab its cursor, for this
# sample we'll just use the first document.
document_cursor = document.cursor
break
# Start the next search from the document of interest.
if document_cursor is None:
return
options = search.QueryOptions(cursor=document_cursor)
query = search.Query(query_string=query_string, options=options)
results = index.search(query)
for document in results:
print(document)
def saving_and_restoring_cursor(cursor):
# Convert the cursor to a web-safe string.
cursor_string = cursor.web_safe_string
# Restore the cursor from a web-safe string.
cursor = search.Cursor(web_safe_string=cursor_string)
def add_faceted_document(index):
document = search.Document(
doc_id='doc1',
fields=[
search.AtomField(name='name', value='x86')],
facets=[
search.AtomFacet(name='type', value='computer'),
search.NumberFacet(name='ram_size_gb', value=8)])
index.put(document)
def facet_discovery(index):
# Create the query and enable facet discovery.
query = search.Query('name:x86', enable_facet_discovery=True)
results = index.search(query)
for facet in results.facets:
print('facet {}.'.format(facet.name))
for value in facet.values:
print('{}: count={}, refinement_token={}'.format(
value.label, value.count, value.refinement_token))
def facet_by_name(index):
# Create the query and specify to only return the "type" and "ram_size_gb"
# facets.
query = search.Query('name:x86', return_facets=['type', 'ram_size_gb'])
results = index.search(query)
for facet in results.facets:
print('facet {}'.format(facet.name))
for value in facet.values:
print('{}: count={}, refinement_token={}'.format(
value.label, value.count, value.refinement_token))
def facet_by_name_and_value(index):
# Create the query and specify to return the "type" facet with values
# "computer" and "printer" and the "ram_size_gb" facet with value in the
# ranges [0,4), [4, 8), and [8, max].
query = search.Query(
'name:x86',
return_facets=[
search.FacetRequest('type', values=['computer', 'printer']),
search.FacetRequest('ram_size_gb', ranges=[
search.FacetRange(end=4),
search.FacetRange(start=4, end=8),
search.FacetRange(start=8)])
])
results = index.search(query)
for facet in results.facets:
print('facet {}'.format(facet.name))
for value in facet.values:
print('{}: count={}, refinement_token={}'.format(
value.label, value.count, value.refinement_token))