Skip to content

Instantly share code, notes, and snippets.

@nicksnell
Created May 2, 2019 16:34
Show Gist options
  • Save nicksnell/0c8cde5fb6e6727c15a3ed9464bf9492 to your computer and use it in GitHub Desktop.
Save nicksnell/0c8cde5fb6e6727c15a3ed9464bf9492 to your computer and use it in GitHub Desktop.
Tool for updating breed bands
"""
Tool for creating breed band mappings & updating the Algolia Index
Install:
pip install --upgrade 'algoliasearch>=2.0,<3.0'
Usage:
ALGOLIA_APP_ID= ALGOLIA_API_KEY= ALGOLIA_INDEX= python breed_bands.py
"""
import os
import csv
import json
import logging
from algoliasearch.search_client import SearchClient
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
def create_breed_mappings(breeds):
"""
Create a JSON file with the breed mappings
"""
breed_mapping = {}
for breed in breeds:
breed_mapping[breed[1].upper()] = breed[3]
with open('breed_bands_mappings.json', 'w+') as mappings:
mappings.write(json.dumps(breed_mapping))
logger.info('Created breed mappings.')
def update_algolia_index(breeds):
"""
Update the Algolia index
"""
client = SearchClient.create(
os.environ.get('ALGOLIA_APP_ID'),
os.environ.get('ALGOLIA_API_KEY')
)
index = client.init_index(os.environ.get('ALGOLIA_INDEX'))
breeds_to_update = []
for breed in breeds:
breeds_to_update.append({
'objectID': breed[1].upper(),
'name': breed[2],
'species': breed[0],
})
index.save_objects(breeds_to_update)
logger.info('Updated breeds.')
def main():
"""
Expected CSV format:
SPECIES, BREED_CODE, NAME, BAND
"""
with open('breed_bands_breeds.csv', 'r') as csvfile:
breeds = list(csv.reader(csvfile))
update_algolia_index(breeds)
create_breed_mappings(breeds)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment