forked from sofastack/sofastack.tech
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hugo_algolia.py
executable file
·74 lines (56 loc) · 2.09 KB
/
hugo_algolia.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from algoliasearch import algoliasearch
import json
import os
import sys
def get_admin_key():
if sys.argv[-1].startswith('ALGOLIA_API_KEY'):
ADMIN_API_KEY = sys.argv[-1].split('=')[1].strip()
else:
ADMIN_API_KEY = os.environ.get('ALGOLIA_API_KEY')
if not ADMIN_API_KEY:
raise Exception("ALGOLIA_API_KEY lacked")
return ADMIN_API_KEY
# fill them
APPLICATION_ID = 'G2HVBB5ERN'
SEARCH_ONLY_API_KEY = '4b161290c268b4eeb154171c562aa1e4'
INDEX_NAME = 'sofastack'
ADMIN_API_KEY = get_admin_key()
def client_for_search_only():
return algoliasearch.Client(APPLICATION_ID, SEARCH_ONLY_API_KEY)
def client_for_admin():
return algoliasearch.Client(APPLICATION_ID, ADMIN_API_KEY)
def get_all_objectID(index_name):
client = client_for_admin()
index = client.init_index(index_name)
res = list(index.browse_all(params={'attributesToRetrieve': 'objectID'}))
all_objectID = [row.get('objectID') for row in res]
return all_objectID
def update_index_of_mysite():
# your json filename
filename = '../public/algolia.json'
rows = json.load(open(filename))
print('update algolia index')
client = client_for_admin()
index = client.init_index(INDEX_NAME)
rows_ids = [row['objectID'] for row in rows]
all_ids = get_all_objectID(INDEX_NAME)
ids_to_delete = list(set(all_ids) - set(rows_ids))
index.delete_objects(ids_to_delete)
index.save_objects(rows)
index.set_settings({"searchableAttributes": ["title", "summary"]})
index.set_settings({'attributesToHighlight': ["title", "summary"]})
index.set_settings({'attributesToSnippet': ['title', 'summary']})
# for highlight
index.set_settings({'highlightPreTag': '<em class="ais-Highlight">', 'highlightPostTag': '</em>'})
return {'delete': len(ids_to_delete), 'save': len(rows)}
def main():
res = update_index_of_mysite()
print(res)
if __name__ == '__main__':
main()
# pip install algoliasearch==1.6.8
# python hugo_algolia.py ALGOLIA_API_KEY="ADMIN_API_KEY"
# https://jeremyyin.com
# jeremyyin2012@gmail.com