-
Notifications
You must be signed in to change notification settings - Fork 12
/
graphql_safegraph.py
275 lines (239 loc) · 6.94 KB
/
graphql_safegraph.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
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
# We use three Python packages to get data from SafeGraph - `gql`, `requests`, and `safegraphql`. We elected to signal the start of each type of API request with the package imports spread throughout the script.
# We will focus on the `gql` or `requests` examples for our work. We will stay in `gql` and highly recommend that you don't use `graphql`.
# %%
# import sys
# !{sys.executable} -m pip install --pre gql
# !{sys.executable} -m pip install requests-toolbelt
# %%
# https://docs.safegraph.com/reference#places-api-overview-new
# https://stackoverflow.com/questions/56856005/how-to-set-environment-variable-in-databricks/56863551
import pandas as pd
import json
import os
from dotenv import load_dotenv
load_dotenv()
sfkey = os.environ.get("SAFEGRAPH_KEY")
# %%
url = 'https://api.safegraph.com/v2/graphql'
query = """
query {
search(
filter: {
address: {
city: "San Francisco",
region: "CA"
}
}
) {
places {
results(first: 25 after: "") {
pageInfo {hasNextPage, endCursor}
edges {
node {
safegraph_core {
placekey
latitude
longitude
street_address
city
region
postal_code
parent_placekey
location_name
naics_code
opened_on
closed_on
}
}
}
}
}
}
}
"""
# old safegraph_weekly_patterns()
query2 = """query {
search(filter: {
naics_code: 813110,
address: {
region: "UT"
}
}){
places {
results(first: 25 after: "") {
pageInfo { hasNextPage, endCursor}
edges {
node {
safegraph_weekly_patterns (date: "2021-07-12") {
placekey
parent_placekey
location_name
street_address
city
region
postal_code
iso_country_code
date_range_start
date_range_end
raw_visit_counts
raw_visitor_counts
poi_cbg
visitor_home_cbgs
visitor_home_aggregation
visitor_daytime_cbgs
visitor_country_of_origin
distance_from_home
median_dwell
bucketed_dwell_times
related_same_day_brand
related_same_week_brand
}
}
}
}
}
}
}
"""
# uses the new weekly_patterns () function.
query3 = """query {
search(
filter: {
address: {
city: "San Francisco",
region: "CA"
}
}
){
places {
results(first: 25 after: "") {
pageInfo { hasNextPage, endCursor}
edges {
node {
weekly_patterns (start_date: "2019-01-07" end_date: "2019-01-13") {
placekey
parent_placekey
location_name
street_address
city
region
postal_code
iso_country_code
date_range_start
date_range_end
raw_visit_counts
raw_visitor_counts
poi_cbg
distance_from_home
median_dwell
}
}
}
}
}
}
}
"""
# %%
# Using the requests package
import requests
r = requests.post(
url,
json={'query': query},
headers = {'Content-Type': 'application/json', 'apikey':sfkey})
# %%
print(r.status_code)
print(r.text)
json_data = json.loads(r.text)
df_data = json_data['data']['search']['places']['results']['edges']
print(df_data)
# %%
pract = df_data.copy()
pd.json_normalize(pract)
# %%
# https://gql.readthedocs.io/en/v3.0.0a6/
# https://github.com/graphql-python/gql
from gql import gql, Client
from gql.transport.requests import RequestsHTTPTransport
# Select your transport with a defined url endpoint
transport = RequestsHTTPTransport(
url=url,
verify=True,
retries=3,
headers={'Content-Type': 'application/json', 'apikey': sfkey})
client = Client(transport=transport, fetch_schema_from_transport=True)
# %%
results = client.execute(gql(query))
results2 = client.execute(gql(query2))
results3 = client.execute(gql(query3))
# %%
edges = results['search']['places']['results']['edges']
resultsNorm = [dat.pop('node') for dat in edges]
resultsNorm = [dat.pop('safegraph_core') for dat in resultsNorm]
dat = pd.json_normalize(resultsNorm)
# %%
edges2 = results2['search']['places']['results']['edges']
resultsNorm = [dat.pop('node') for dat in edges2]
resultsNorm = [dat.pop('safegraph_weekly_patterns') for dat in resultsNorm]
dat = pd.json_normalize(resultsNorm)
# %%
edges3 = results3['search']['places']['results']['edges']
resultsNorm = [dat.pop('node') for dat in edges3]
resultsNorm = [dat.pop('weekly_patterns') for dat in resultsNorm]
resultsNorm_flat = [dat[0] for dat in resultsNorm if dat is not None]
dat = pd.json_normalize(resultsNorm_flat)
# %%
# Don't use
# https://pypi.org/project/safegraphQL/
# import sys
# !{sys.executable} -m pip install safegraphQL
# %%
# https://pypi.org/project/safegraphQL/
# https://github.com/echong-SG/API-python-client-MKilic
# import safegraphql.client as sgql
# sgql_client = sgql.HTTP_Client(apikey = sfkey)
# # %%
# pks = [
# 'zzw-222@8fy-fjg-b8v', # Disney World
# 'zzw-222@5z6-3h9-tsq' # LAX
# ]
# cols = [
# 'location_name',
# 'street_address',
# 'city',
# 'region',
# 'postal_code',
# 'iso_country_code'
# ]
# sgql_client.lookup(product = 'core', placekeys = pks, columns = cols)
# # %%
# sgql_client.lookup(product = 'core', placekeys = pks, columns = "*")
# # %%
# geo = sgql_client.lookup(product = 'geometry', placekeys = pks, columns = '*')
# patterns = sgql_client.lookup(product = 'monthly_patterns', placekeys = pks, columns = '*')
# # %%
# watterns = sgql_client.lookup(product = 'weekly_patterns', placekeys = pk, columns = '*')
# # %%
# ## weekly patterns
# dates = ['2019-06-15', '2019-06-16', '2021-05-23', '2018-10-23']
# sgql_client.lookup(
# product = 'weekly_patterns',
# placekeys = pks,
# date = dates,
# columns = ['placekey', 'location_name', 'date_range_start', 'date_range_end', 'raw_visit_counts']
# )
# # %%
# dates = {'date_range_start': '2019-04-10', 'date_range_end': '2019-06-05'}
# watterns = sgql_client.lookup(
# product = 'weekly_patterns',
# placekeys = pks,
# date = dates,
# columns = ['placekey', 'location_name', 'date_range_start', 'date_range_end', 'raw_visit_counts']
# )
# core = sgql_client.lookup(product = 'core', placekeys = pks, columns = ['placekey', 'location_name', 'naics_code', 'top_category', 'sub_category'])
# geo = sgql_client.lookup(product = 'geometry', placekeys = pks, columns = ['placekey', 'polygon_class', 'enclosed'])
# # %%
# merged = sgql_client.sg_merge(datasets = [core, geo, watterns])
# # %%
# # look-up by name
# # https://github.com/echong-SG/API-python-client-MKilic#lookup_by_name