-
Notifications
You must be signed in to change notification settings - Fork 234
/
suggest.py
51 lines (40 loc) · 1.57 KB
/
suggest.py
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
import logging
import azure.functions as func
from azure.core.credentials import AzureKeyCredential
from azure.search.documents import SearchClient
from shared_code import azure_config
import json
environment_vars = azure_config()
# curl --header "Content-Type: application/json" \
# --request POST \
# --data '{"q":"code","top":"5", "suggester":"sg"}' \
# http://localhost:7071/api/Suggest
# Set Azure Search endpoint and key
service_name = environment_vars["search_service_name"]
endpoint = f"https://{service_name}.search.windows.net"
key = environment_vars["search_api_key"]
# Your index name
index_name = "good-books"
# Create Azure SDK client
search_client = SearchClient(endpoint, index_name, AzureKeyCredential(key))
bp=func.Blueprint()
@bp.function_name("suggest")
@bp.route(route="suggest", methods=[func.HttpMethod.GET, func.HttpMethod.POST] )
def main(req: func.HttpRequest) -> func.HttpResponse:
# variables sent in body
req_body = req.get_json()
q = req_body.get("q")
top = req_body.get("top") or 5
suggester = req_body.get("suggester") or "sg"
if q:
logging.info("/Suggest q = %s", q)
suggestions = search_client.suggest(search_text=q, suggester_name=suggester, top=top)
# format the React app expects
full_response = {}
full_response["suggestions"] = suggestions
logging.debug(suggestions)
return func.HttpResponse(
body=json.dumps(full_response), mimetype="application/json", status_code=200
)
else:
return func.HttpResponse("No query param found.", status_code=200)