Skip to content

Commit be079df

Browse files
authored
support list for select argument (Azure#14991)
* support list for select argument * update
1 parent 13eb032 commit be079df

9 files changed

+504
-8
lines changed

sdk/search/azure-search-documents/azure/search/documents/_internal/_queries.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,3 +99,16 @@ class SuggestQuery(_QueryBase):
9999
_request_type = SuggestRequest
100100

101101
__doc__ = SuggestRequest.__doc__
102+
103+
def select(self, *fields):
104+
# type: (*str) -> None
105+
"""Update the `select` property for the search results.
106+
107+
:param fields: An list of fields for the query result to return.
108+
:type expression: str
109+
:raises: ValueError
110+
"""
111+
if not fields:
112+
raise ValueError("At least one field must be provided")
113+
114+
self._request.select = ",".join(fields)

sdk/search/azure-search-documents/azure/search/documents/_internal/_search_client.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
# license information.
55
# --------------------------------------------------------------------------
66
from typing import cast, List, TYPE_CHECKING
7-
87
import six
98

109
from azure.core.tracing.decorator import distributed_trace
@@ -261,10 +260,12 @@ def search(self, search_text, **kwargs):
261260
scoring_profile=scoring_profile,
262261
search_fields=search_fields,
263262
search_mode=search_mode,
264-
select=select,
263+
select=select if isinstance(select, six.string_types) else None,
265264
skip=skip,
266265
top=top
267266
)
267+
if isinstance(select, list):
268+
query.select(select)
268269

269270
kwargs["headers"] = self._merge_client_headers(kwargs.get("headers"))
270271
return SearchItemPaged(
@@ -336,10 +337,11 @@ def suggest(self, search_text, suggester_name, **kwargs):
336337
minimum_coverage=minimum_coverage,
337338
order_by=order_by,
338339
search_fields=search_fields,
339-
select=select,
340+
select=select if isinstance(select, six.string_types) else None,
340341
top=top
341342
)
342-
343+
if isinstance(select, list):
344+
query.select(select)
343345
kwargs["headers"] = self._merge_client_headers(kwargs.get("headers"))
344346
response = self._client.documents.suggest_post(
345347
suggest_request=query.request, **kwargs

sdk/search/azure-search-documents/azure/search/documents/_internal/aio/_search_client_async.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
# license information.
55
# --------------------------------------------------------------------------
66
from typing import cast, List, TYPE_CHECKING
7+
import six
78

89
from azure.core.tracing.decorator_async import distributed_trace_async
910
from ._paging import AsyncSearchItemPaged, AsyncSearchPageIterator
@@ -223,11 +224,12 @@ async def search(self, search_text, **kwargs):
223224
scoring_profile=scoring_profile,
224225
search_fields=search_fields,
225226
search_mode=search_mode,
226-
select=select,
227+
select=select if isinstance(select, six.string_types) else None,
227228
skip=skip,
228229
top=top
229230
)
230-
231+
if isinstance(select, list):
232+
query.select(select)
231233
kwargs["headers"] = self._merge_client_headers(kwargs.get("headers"))
232234
return AsyncSearchItemPaged(
233235
self._client, query, kwargs, page_iterator_class=AsyncSearchPageIterator
@@ -298,10 +300,11 @@ async def suggest(self, search_text, suggester_name, **kwargs):
298300
minimum_coverage=minimum_coverage,
299301
order_by=order_by,
300302
search_fields=search_fields,
301-
select=select,
303+
select=select if isinstance(select, six.string_types) else None,
302304
top=top
303305
)
304-
306+
if isinstance(select, list):
307+
query.select(select)
305308
kwargs["headers"] = self._merge_client_headers(kwargs.get("headers"))
306309
response = await self._client.documents.suggest_post(
307310
suggest_request=query.request, **kwargs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
interactions:
2+
- request:
3+
body: '{"filter": "category eq ''Budget''", "orderby": "hotelName desc", "search":
4+
"WiFi", "select": "hotelName,category,description"}'
5+
headers:
6+
Accept:
7+
- application/json;odata.metadata=none
8+
Content-Length:
9+
- '125'
10+
Content-Type:
11+
- application/json
12+
User-Agent:
13+
- azsdk-python-search-documents/11.1.0b2 Python/3.8.5 (Windows-10-10.0.19041-SP0)
14+
method: POST
15+
uri: https://search6e521a9a.search.windows.net/indexes('drgqefsg')/docs/search.post.search?api-version=2020-06-30
16+
response:
17+
body:
18+
string: '{"value":[{"@search.score":1.0225849,"hotelName":"Express Rooms","description":"Pretty
19+
good hotel","category":"Budget"},{"@search.score":1.0225849,"hotelName":"EconoStay","description":"Very
20+
popular hotel in town","category":"Budget"},{"@search.score":2.3832736,"hotelName":"Countryside
21+
Hotel","description":"Save up to 50% off traditional hotels. Free WiFi, great
22+
location near downtown, full kitchen, washer & dryer, 24/7 support, bowling
23+
alley, fitness center and more.","category":"Budget"},{"@search.score":1.0225849,"hotelName":"Comfy
24+
Place","description":"Another good hotel","category":"Budget"}]}'
25+
headers:
26+
cache-control: no-cache
27+
content-encoding: gzip
28+
content-length: '442'
29+
content-type: application/json; odata.metadata=none
30+
date: Fri, 28 Aug 2020 21:07:31 GMT
31+
elapsed-time: '73'
32+
expires: '-1'
33+
odata-version: '4.0'
34+
pragma: no-cache
35+
preference-applied: odata.include-annotations="*"
36+
request-id: 7c9fee41-e972-11ea-9d02-5cf37071153c
37+
strict-transport-security: max-age=15724800; includeSubDomains
38+
vary: Accept-Encoding
39+
status:
40+
code: 200
41+
message: OK
42+
url: https://search6e521a9a.search.windows.net/indexes('drgqefsg')/docs/search.post.search?api-version=2020-06-30
43+
version: 1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
interactions:
2+
- request:
3+
body: '{"search": "hotel"}'
4+
headers:
5+
Accept:
6+
- application/json;odata.metadata=none
7+
Content-Length:
8+
- '19'
9+
Content-Type:
10+
- application/json
11+
User-Agent:
12+
- azsdk-python-search-documents/11.1.0b2 Python/3.8.5 (Windows-10-10.0.19041-SP0)
13+
method: POST
14+
uri: https://search6e8a1a80.search.windows.net/indexes('drgqefsg')/docs/search.post.search?api-version=2020-06-30
15+
response:
16+
body:
17+
string: '{"value":[{"@search.score":2.245087,"hotelId":"10","hotelName":"Countryside
18+
Hotel","description":"Save up to 50% off traditional hotels. Free WiFi, great
19+
location near downtown, full kitchen, washer & dryer, 24/7 support, bowling
20+
alley, fitness center and more.","descriptionFr":"\u00c9conomisez jusqu''\u00e0
21+
50% sur les h\u00f4tels traditionnels. WiFi gratuit, tr\u00e8s bien situ\u00e9
22+
pr\u00e8s du centre-ville, cuisine compl\u00e8te, laveuse & s\u00e9cheuse,
23+
support 24/7, bowling, centre de fitness et plus encore.","category":"Budget","tags":["24-hour
24+
front desk service","coffee in lobby","restaurant"],"parkingIncluded":false,"smokingAllowed":true,"lastRenovationDate":"1999-09-06T00:00:00Z","rating":3,"location":{"type":"Point","coordinates":[-78.940483,35.90416],"crs":{"type":"name","properties":{"name":"EPSG:4326"}}},"address":{"streetAddress":"6910
25+
Fayetteville Rd","city":"Durham","stateProvince":"NC","country":"USA","postalCode":"27713"},"rooms":[{"description":"Suite,
26+
1 King Bed (Amenities)","descriptionFr":"Suite, 1 tr\u00e8s grand lit (Services)","type":"Suite","baseRate":2.44,"bedOptions":"1
27+
King Bed","sleepsCount":2,"smokingAllowed":true,"tags":["coffee maker"]},{"description":"Budget
28+
Room, 1 Queen Bed (Amenities)","descriptionFr":"Chambre \u00c9conomique, 1
29+
grand lit (Services)","type":"Budget Room","baseRate":7.69,"bedOptions":"1
30+
Queen Bed","sleepsCount":2,"smokingAllowed":false,"tags":["coffee maker"]}]},{"@search.score":1.778081,"hotelId":"3","hotelName":"EconoStay","description":"Very
31+
popular hotel in town","descriptionFr":"H\u00f4tel le plus populaire en ville","category":"Budget","tags":["wifi","budget"],"parkingIncluded":true,"smokingAllowed":false,"lastRenovationDate":"1995-07-01T00:00:00Z","rating":4,"location":{"type":"Point","coordinates":[-122.131577,46.678581],"crs":{"type":"name","properties":{"name":"EPSG:4326"}}},"address":null,"rooms":[]},{"@search.score":1.778081,"hotelId":"4","hotelName":"Express
32+
Rooms","description":"Pretty good hotel","descriptionFr":"Assez bon h\u00f4tel","category":"Budget","tags":["wifi","budget"],"parkingIncluded":true,"smokingAllowed":false,"lastRenovationDate":"1995-07-01T00:00:00Z","rating":4,"location":{"type":"Point","coordinates":[-122.131577,48.678581],"crs":{"type":"name","properties":{"name":"EPSG:4326"}}},"address":null,"rooms":[]},{"@search.score":1.778081,"hotelId":"5","hotelName":"Comfy
33+
Place","description":"Another good hotel","descriptionFr":"Un autre bon h\u00f4tel","category":"Budget","tags":["wifi","budget"],"parkingIncluded":true,"smokingAllowed":false,"lastRenovationDate":"2012-08-12T00:00:00Z","rating":4,"location":{"type":"Point","coordinates":[-122.131577,48.678581],"crs":{"type":"name","properties":{"name":"EPSG:4326"}}},"address":null,"rooms":[]},{"@search.score":1.5749159,"hotelId":"2","hotelName":"Roach
34+
Motel","description":"Cheapest hotel in town. Infact, a motel.","descriptionFr":"H\u00f4tel
35+
le moins cher en ville. Infact, un motel.","category":"Budget","tags":["motel","budget"],"parkingIncluded":true,"smokingAllowed":true,"lastRenovationDate":"1982-04-28T00:00:00Z","rating":1,"location":{"type":"Point","coordinates":[-122.131577,49.678581],"crs":{"type":"name","properties":{"name":"EPSG:4326"}}},"address":null,"rooms":[]},{"@search.score":1.4634744,"hotelId":"1","hotelName":"Fancy
36+
Stay","description":"Best hotel in town if you like luxury hotels. They have
37+
an amazing infinity pool, a spa, and a really helpful concierge. The location
38+
is perfect -- right downtown, close to all the tourist attractions. We highly
39+
recommend this hotel.","descriptionFr":"Meilleur h\u00f4tel en ville si vous
40+
aimez les h\u00f4tels de luxe. Ils ont une magnifique piscine \u00e0 d\u00e9bordement,
41+
un spa et un concierge tr\u00e8s utile. L''emplacement est parfait \u2013
42+
en plein centre, \u00e0 proximit\u00e9 de toutes les attractions touristiques.
43+
Nous recommandons fortement cet h\u00f4tel.","category":"Luxury","tags":["pool","view","wifi","concierge"],"parkingIncluded":false,"smokingAllowed":false,"lastRenovationDate":"2010-06-27T00:00:00Z","rating":5,"location":{"type":"Point","coordinates":[-122.131577,47.678581],"crs":{"type":"name","properties":{"name":"EPSG:4326"}}},"address":null,"rooms":[]},{"@search.score":0.5496142,"hotelId":"9","hotelName":"Secret
44+
Point Motel","description":"The hotel is ideally located on the main commercial
45+
artery of the city in the heart of New York. A few minutes away is Time''s
46+
Square and the historic centre of the city, as well as other places of interest
47+
that make New York one of America''s most attractive and cosmopolitan cities.","descriptionFr":"L''h\u00f4tel
48+
est id\u00e9alement situ\u00e9 sur la principale art\u00e8re commerciale de
49+
la ville en plein c\u0153ur de New York. A quelques minutes se trouve la place
50+
du temps et le centre historique de la ville, ainsi que d''autres lieux d''int\u00e9r\u00eat
51+
qui font de New York l''une des villes les plus attractives et cosmopolites
52+
de l''Am\u00e9rique.","category":"Boutique","tags":["pool","air conditioning","concierge"],"parkingIncluded":false,"smokingAllowed":true,"lastRenovationDate":"1970-01-18T05:00:00Z","rating":4,"location":{"type":"Point","coordinates":[-73.975403,40.760586],"crs":{"type":"name","properties":{"name":"EPSG:4326"}}},"address":{"streetAddress":"677
53+
5th Ave","city":"New York","stateProvince":"NY","country":"USA","postalCode":"10022"},"rooms":[{"description":"Budget
54+
Room, 1 Queen Bed (Cityside)","descriptionFr":"Chambre \u00c9conomique, 1
55+
grand lit (c\u00f4t\u00e9 ville)","type":"Budget Room","baseRate":9.69,"bedOptions":"1
56+
Queen Bed","sleepsCount":2,"smokingAllowed":true,"tags":["vcr/dvd"]},{"description":"Budget
57+
Room, 1 King Bed (Mountain View)","descriptionFr":"Chambre \u00c9conomique,
58+
1 tr\u00e8s grand lit (Mountain View)","type":"Budget Room","baseRate":8.09,"bedOptions":"1
59+
King Bed","sleepsCount":2,"smokingAllowed":true,"tags":["vcr/dvd","jacuzzi
60+
tub"]}]}]}'
61+
headers:
62+
cache-control: no-cache
63+
content-encoding: gzip
64+
content-length: '2378'
65+
content-type: application/json; odata.metadata=none
66+
date: Fri, 28 Aug 2020 21:07:53 GMT
67+
elapsed-time: '83'
68+
expires: '-1'
69+
odata-version: '4.0'
70+
pragma: no-cache
71+
preference-applied: odata.include-annotations="*"
72+
request-id: 8a56c06f-e972-11ea-a554-5cf37071153c
73+
strict-transport-security: max-age=15724800; includeSubDomains
74+
vary: Accept-Encoding
75+
status:
76+
code: 200
77+
message: OK
78+
url: https://search6e8a1a80.search.windows.net/indexes('drgqefsg')/docs/search.post.search?api-version=2020-06-30
79+
- request:
80+
body: '{"search": "motel"}'
81+
headers:
82+
Accept:
83+
- application/json;odata.metadata=none
84+
Content-Length:
85+
- '19'
86+
Content-Type:
87+
- application/json
88+
User-Agent:
89+
- azsdk-python-search-documents/11.1.0b2 Python/3.8.5 (Windows-10-10.0.19041-SP0)
90+
method: POST
91+
uri: https://search6e8a1a80.search.windows.net/indexes('drgqefsg')/docs/search.post.search?api-version=2020-06-30
92+
response:
93+
body:
94+
string: '{"value":[{"@search.score":8.376183,"hotelId":"2","hotelName":"Roach
95+
Motel","description":"Cheapest hotel in town. Infact, a motel.","descriptionFr":"H\u00f4tel
96+
le moins cher en ville. Infact, un motel.","category":"Budget","tags":["motel","budget"],"parkingIncluded":true,"smokingAllowed":true,"lastRenovationDate":"1982-04-28T00:00:00Z","rating":1,"location":{"type":"Point","coordinates":[-122.131577,49.678581],"crs":{"type":"name","properties":{"name":"EPSG:4326"}}},"address":null,"rooms":[]},{"@search.score":0.8858137,"hotelId":"9","hotelName":"Secret
97+
Point Motel","description":"The hotel is ideally located on the main commercial
98+
artery of the city in the heart of New York. A few minutes away is Time''s
99+
Square and the historic centre of the city, as well as other places of interest
100+
that make New York one of America''s most attractive and cosmopolitan cities.","descriptionFr":"L''h\u00f4tel
101+
est id\u00e9alement situ\u00e9 sur la principale art\u00e8re commerciale de
102+
la ville en plein c\u0153ur de New York. A quelques minutes se trouve la place
103+
du temps et le centre historique de la ville, ainsi que d''autres lieux d''int\u00e9r\u00eat
104+
qui font de New York l''une des villes les plus attractives et cosmopolites
105+
de l''Am\u00e9rique.","category":"Boutique","tags":["pool","air conditioning","concierge"],"parkingIncluded":false,"smokingAllowed":true,"lastRenovationDate":"1970-01-18T05:00:00Z","rating":4,"location":{"type":"Point","coordinates":[-73.975403,40.760586],"crs":{"type":"name","properties":{"name":"EPSG:4326"}}},"address":{"streetAddress":"677
106+
5th Ave","city":"New York","stateProvince":"NY","country":"USA","postalCode":"10022"},"rooms":[{"description":"Budget
107+
Room, 1 Queen Bed (Cityside)","descriptionFr":"Chambre \u00c9conomique, 1
108+
grand lit (c\u00f4t\u00e9 ville)","type":"Budget Room","baseRate":9.69,"bedOptions":"1
109+
Queen Bed","sleepsCount":2,"smokingAllowed":true,"tags":["vcr/dvd"]},{"description":"Budget
110+
Room, 1 King Bed (Mountain View)","descriptionFr":"Chambre \u00c9conomique,
111+
1 tr\u00e8s grand lit (Mountain View)","type":"Budget Room","baseRate":8.09,"bedOptions":"1
112+
King Bed","sleepsCount":2,"smokingAllowed":true,"tags":["vcr/dvd","jacuzzi
113+
tub"]}]}]}'
114+
headers:
115+
cache-control: no-cache
116+
content-encoding: gzip
117+
content-length: '1269'
118+
content-type: application/json; odata.metadata=none
119+
date: Fri, 28 Aug 2020 21:07:55 GMT
120+
elapsed-time: '7'
121+
expires: '-1'
122+
odata-version: '4.0'
123+
pragma: no-cache
124+
preference-applied: odata.include-annotations="*"
125+
request-id: 8ac67395-e972-11ea-9c35-5cf37071153c
126+
strict-transport-security: max-age=15724800; includeSubDomains
127+
vary: Accept-Encoding
128+
status:
129+
code: 200
130+
message: OK
131+
url: https://search6e8a1a80.search.windows.net/indexes('drgqefsg')/docs/search.post.search?api-version=2020-06-30
132+
version: 1

sdk/search/azure-search-documents/tests/async_tests/test_search_client_search_live_async.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,23 @@ async def test_get_search_simple(self, api_key, endpoint, index_name, **kwargs):
5858
results.append(x)
5959
assert len(results) == 2
6060

61+
@ResourceGroupPreparer(random_name_enabled=True)
62+
@SearchServicePreparer(schema=SCHEMA, index_batch=BATCH)
63+
async def test_get_search_simple_paged(self, api_key, endpoint, index_name, **kwargs):
64+
client = SearchClient(
65+
endpoint, index_name, AzureKeyCredential(api_key)
66+
)
67+
async with client:
68+
results = []
69+
async for x in await client.search(search_text="hotel", top=3):
70+
results.append(x)
71+
assert len(results) == 7
72+
73+
results = []
74+
async for x in await client.search(search_text="motel"):
75+
results.append(x)
76+
assert len(results) == 2
77+
6178
@ResourceGroupPreparer(random_name_enabled=True)
6279
@SearchServicePreparer(schema=SCHEMA, index_batch=BATCH)
6380
async def test_get_search_filter(self, api_key, endpoint, index_name, **kwargs):
@@ -88,6 +105,36 @@ async def test_get_search_filter(self, api_key, endpoint, index_name, **kwargs):
88105
assert all(set(x) == expected for x in results)
89106
assert all(x["category"] == "Budget" for x in results)
90107

108+
@ResourceGroupPreparer(random_name_enabled=True)
109+
@SearchServicePreparer(schema=SCHEMA, index_batch=BATCH)
110+
async def test_get_search_filter_array(self, api_key, endpoint, index_name, **kwargs):
111+
client = SearchClient(
112+
endpoint, index_name, AzureKeyCredential(api_key)
113+
)
114+
115+
async with client:
116+
results = []
117+
select = ("hotelName", "category", "description")
118+
async for x in await client.search(
119+
search_text="WiFi",
120+
filter="category eq 'Budget'",
121+
select=select,
122+
order_by="hotelName desc"
123+
):
124+
results.append(x)
125+
assert [x["hotelName"] for x in results] == sorted(
126+
[x["hotelName"] for x in results], reverse=True
127+
)
128+
expected = {
129+
"category",
130+
"hotelName",
131+
"description",
132+
"@search.score",
133+
"@search.highlights",
134+
}
135+
assert all(set(x) == expected for x in results)
136+
assert all(x["category"] == "Budget" for x in results)
137+
91138
@ResourceGroupPreparer(random_name_enabled=True)
92139
@SearchServicePreparer(schema=SCHEMA, index_batch=BATCH)
93140
async def test_get_search_counts(self, api_key, endpoint, index_name, **kwargs):

0 commit comments

Comments
 (0)