-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsearch_facets.py
More file actions
executable file
·125 lines (103 loc) · 3.43 KB
/
search_facets.py
File metadata and controls
executable file
·125 lines (103 loc) · 3.43 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
#!/usr/bin/env python3
"""
Faceted search example.
Issues an initial query that requests facets, prints the available filter
values per facet, then issues a follow-up query that narrows the result set
using one of those facet values as a filter.
Requires:
pip install requests
Usage:
python search_facets.py
"""
import sys
import requests
# ---------------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------------
BASE_URL = "https://<your-instance>/sabio-web/services"
USERNAME = "<username>"
PASSWORD = "<password>"
QUERY = "vacation"
FACETS = ["resource", "language"]
def login(base_url: str, username: str, password: str) -> str:
response = requests.post(
f"{base_url}/authentication/credentials",
json={"login": username, "key": password},
headers={"Content-Type": "application/json; charset=utf-8"},
timeout=30,
)
response.raise_for_status()
token = response.json().get("data", {}).get("key")
if not token:
raise RuntimeError(f"Login failed: {response.text}")
return token
def search(base_url: str, token: str, body: dict) -> dict:
response = requests.post(
f"{base_url}/search",
json=body,
headers={
"Content-Type": "application/json; charset=utf-8",
"sabio-auth-token": token,
},
timeout=30,
)
response.raise_for_status()
return response.json()
def print_facets(payload: dict) -> None:
facets = payload.get("data", {}).get("filter", []) or []
if not facets:
print("(no facets returned)")
return
for facet in facets:
print(f"\nFacet: {facet.get('title')} (property={facet.get('property')})")
for value in facet.get("values", []) or []:
print(
f" - {value.get('title')} "
f"(value={value.get('value')}, count={value.get('count')})"
)
def main() -> int:
token = login(BASE_URL, USERNAME, PASSWORD)
# Step 1: initial search with facets requested.
initial = search(
BASE_URL,
token,
{
"query": QUERY,
"limit": 5,
"facets": FACETS,
"filterMode": "filtered",
},
)
total = initial.get("data", {}).get("total", 0)
print(f"Query: {QUERY!r} -- {total} total hits.")
print_facets(initial)
# Step 2: pick the first value of the first facet, then re-run with it
# applied as a filter.
facets = initial.get("data", {}).get("filter", []) or []
if not facets or not facets[0].get("values"):
print("\nNothing to drill into; exiting.")
return 0
facet = facets[0]
chosen = facet["values"][0]
print(
f"\nNarrowing on {facet['property']} = {chosen['value']} "
f"(expected {chosen.get('count')} hits)..."
)
narrowed = search(
BASE_URL,
token,
{
"query": QUERY,
"limit": 5,
"filters": [
{"property": facet["property"], "values": [chosen["value"]]}
],
},
)
narrowed_total = narrowed.get("data", {}).get("total", 0)
print(f"Narrowed result: {narrowed_total} hits.")
for hit in narrowed.get("data", {}).get("result", []) or []:
print(f" - [{hit.get('resource', '?')}] {hit.get('title', '<untitled>')}")
return 0
if __name__ == "__main__":
sys.exit(main())