Skip to content

Commit

Permalink
feat(python): guides
Browse files Browse the repository at this point in the history
  • Loading branch information
Fluf22 committed Jan 29, 2025
1 parent bc11607 commit b70b05f
Show file tree
Hide file tree
Showing 15 changed files with 267 additions and 11 deletions.
5 changes: 1 addition & 4 deletions templates/python/guides/ingestion/pushSetup.mustache
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import asyncio
import json
{{> snippets/import}}


async def main():
if __name__ == '__main__':
# use the region matching your applicationID
_{{> snippets/init}}

Expand All @@ -14,5 +13,3 @@ async def main():
resp = {{#dynamicSnippet}}pushSetup{{/dynamicSnippet}}

print(resp)

asyncio.run(main())
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import asyncio
{{> snippets/import}}


async def main():
if __name__ == '__main__':
try:
# You need an API key with `deleteIndex`
_{{> snippets/init}}
Expand All @@ -29,4 +28,3 @@ async def main():
except Exception as e:
print(f"Error: {e}")

asyncio.run(main())
21 changes: 21 additions & 0 deletions templates/python/guides/search/saveObjectsChunks.mustache
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import json

{{> snippets/import}}


if __name__ == '__main__':
try:
_{{> snippets/init}}

with open("records.json", "r", encoding="utf-8") as f:
records = json.load(f)

chunk_size = 10000

for begin_index in range(0, len(records), chunk_size):
chunk = records[begin_index:begin_index + chunk_size]
{{#dynamicSnippet}}saveObjectsChunks{{/dynamicSnippet}}

except Exception as e:
print(f"Error: {e}")

19 changes: 19 additions & 0 deletions templates/python/guides/search/saveObjectsMCM.mustache
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{{> snippets/import}}

def _get_all_app_id_configurations():
return [] # A list of your MCM AppID/ApiKey pairs

if __name__ == '__main__':
playlists = [] # Your records

# Fetch from your own data storage and with your own code
# the list of application IDs and API keys to target each cluster
configurations = _get_all_app_id_configurations()

# Send the records to each cluster
for appID, apiKey in configurations:
try:
_client = SearchClientSync(appID, apiKey)
{{#dynamicSnippet}}saveObjectsPlaylists{{/dynamicSnippet}}
except Exception as e:
print(f"Error: {e}")
29 changes: 29 additions & 0 deletions templates/python/guides/search/saveObjectsModified.mustache
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import json

{{> snippets/import}}


if __name__ == '__main__':
try:
_{{> snippets/init}}

with open("products.json", "r", encoding="utf-8") as f:
products = json.load(f)

records = []

for product in products:
reference = product['product_reference']

suffixes = []
while len(reference) > 1:
reference = reference[1:]
suffixes.append(reference)

product['product_reference_suffixes'] = suffixes
records.append(product)

{{#dynamicSnippet}}saveObjectsRecords{{/dynamicSnippet}}
except Exception as e:
print(f"Error: {e}")

5 changes: 1 addition & 4 deletions templates/python/guides/search/saveObjectsMovies.mustache
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import asyncio
import requests
{{> snippets/import}}


async def main():
if __name__ == '__main__':
# Fetch sample dataset
url = "https://dashboard.algolia.com/api/1/sample_datasets?type=movie"
movies = requests.get(url).json()
Expand All @@ -13,5 +12,3 @@ async def main():

# Save records in Algolia index
{{#dynamicSnippet}}saveObjectsMovies{{/dynamicSnippet}}

asyncio.run(main())
12 changes: 12 additions & 0 deletions templates/python/guides/search/saveObjectsPublicUser.mustache
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{{> snippets/import}}


if __name__ == '__main__':
playlists = [] # Your records

try:
_{{> snippets/init}}

{{#dynamicSnippet}}saveObjectsPlaylistsWithUserIDPublic{{/dynamicSnippet}}
except Exception as e:
print(f"Error: {e}")
26 changes: 26 additions & 0 deletions templates/python/guides/search/savePopularRecords.mustache
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{{> snippets/import}}
from algoliasearch.search.models.browse_response import BrowseResponse


if __name__ == '__main__':
try:
_{{> snippets/init}}

records = []
def _aggregator(resp: BrowseResponse):
for hit in resp.hits:
hit_dict = hit.to_dict()
records.append({
'twitterHandle': hit_dict['twitterHandle'],
'nbFollowers': hit_dict['nbFollowers'],
'isPopular': hit_dict['nbFollowers'] > 1000000,
})

_client.browse_objects(
index_name="<YOUR_INDEX_NAME>",
aggregator=_aggregator,
)

{{#dynamicSnippet}}saveObjectsRecords{{/dynamicSnippet}}
except Exception as e:
print(f"Error: {e}")
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import time

{{> snippets/import}}


if __name__ == '__main__':
try:
_{{> snippets/init}}

date_timestamp = time.time() # Get current timestamp
search_params = {
"query": "<YOUR_SEARCH_QUERY>",
"filters": f"date_timestamp > {date_timestamp}"
}

{{#dynamicSnippet}}searchWithSearchParams{{/dynamicSnippet}}
except Exception as e:
print(f"Error: {e}")
26 changes: 26 additions & 0 deletions templates/python/guides/search/searchWithGAToken.mustache
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{{> snippets/import}}


def _get_google_analytics_user_id_from_browser_cookie(cookie_name: str) -> str:
# Implement your logic here
return ''

if __name__ == '__main__':
try:
_{{> snippets/init}}

user_token = _get_google_analytics_user_id_from_browser_cookie('_ga')
search_params = {
'query': '<YOUR_SEARCH_QUERY>',
'userToken': user_token,
}

{{#dynamicSnippet}}searchWithSearchParams{{/dynamicSnippet}}

logged_in_user = None

search_params['user_token'] = logged_in_user or user_token

{{#dynamicSnippet}}searchWithSearchParams{{/dynamicSnippet}}
except Exception as e:
print(f"Error: {e}")
23 changes: 23 additions & 0 deletions templates/python/guides/search/searchWithOptionalFilters.mustache
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{{> snippets/import}}
from algoliasearch.search.models.search_params import SearchParams


def _reduce_labels_to_filters(_labels):
# Implement your logic here
return []

if __name__ == '__main__':
labels = [] # A list of labels

try:
_{{> snippets/init}}

optional_filters = _reduce_labels_to_filters(labels)
search_params = SearchParams(
query="<YOUR_SEARCH_QUERY>",
optional_filters=optional_filters,
)

{{#dynamicSnippet}}searchWithSearchParams{{/dynamicSnippet}}
except Exception as e:
print(f"Error: {e}")
23 changes: 23 additions & 0 deletions templates/python/guides/search/searchWithRuleContextBuyer.mustache
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{{> snippets/import}}
from algoliasearch.search.models.search_params import SearchParams


def _get_buyer_account_id() -> str:
# Implement your logic here
return ''

if __name__ == '__main__':

try:
_{{> snippets/init}}

# get the buyer account information
buyer = _get_buyer_account_id()
search_params = SearchParams(
query="<YOUR_SEARCH_QUERY>",
rule_contexts=[buyer],
)

{{#dynamicSnippet}}searchWithSearchParams{{/dynamicSnippet}}
except Exception as e:
print(f"Error: {e}")
22 changes: 22 additions & 0 deletions templates/python/guides/search/searchWithRuleContexts.mustache
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{{> snippets/import}}
from algoliasearch.search.models.search_params import SearchParams


def _get_platform_tag() -> str:
# Implement your logic here
return ''

if __name__ == '__main__':
try:
_{{> snippets/init}}

# get the buyer account information
platform_tag = _get_platform_tag()
search_params = SearchParams(
query="<YOUR_SEARCH_QUERY>",
rule_contexts=[platform_tag],
)

{{#dynamicSnippet}}searchWithSearchParams{{/dynamicSnippet}}
except Exception as e:
print(f"Error: {e}")
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{{> snippets/import}}


if __name__ == '__main__':
playlists = [] # Your records

try:
_{{> snippets/init}}

for playlist in playlists:
playlist_user_id = playlist['userID']
{{#dynamicSnippet}}saveObjectsPlaylistsWithRequestOptions{{/dynamicSnippet}}
except Exception as e:
print(f"Error: {e}")
31 changes: 31 additions & 0 deletions templates/python/guides/search/setSettingsThenSaveObjects.mustache
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
{{> snippets/import}}
from algoliasearch.search.models.index_settings import IndexSettings


def _get_app_id_for(_user):
# Implement your own logic here
return ""

def _get_indexing_api_key_for(_user):
# Implement your own logic here
return ""

if __name__ == '__main__':
playlists = [] # Your records

try:
_{{> snippets/init}}

for playlist in playlists:
app_id = _get_app_id_for(playlist['user'])
api_key = _get_indexing_api_key_for(playlist['user'])

_client = SearchClientSync(app_id, api_key)
settings = IndexSettings(
attributes_for_faceting=['filterOnly(user)']
)
{{#dynamicSnippet}}setSettings{{/dynamicSnippet}}

{{#dynamicSnippet}}saveObjectsPlaylists{{/dynamicSnippet}}
except Exception as e:
print(f"Error: {e}")

0 comments on commit b70b05f

Please sign in to comment.