algolia / algoliasearch-client-python

⚡️ A fully-featured and blazing-fast Python API client to interact with Algolia.
https://www.algolia.com/doc/api-client/getting-started/install/python/?language=python
MIT License
196 stars 67 forks source link

KeyError when batch saving rules from browse_rules() #544

Closed ryancambray-ct closed 1 year ago

ryancambray-ct commented 2 years ago

Description

I'm creating a script that will copy an application's search rules for all indices and clone them to other applications within our algolia stack. To do this, after initialising the client and selecting an index, I'm using the rules methods browse_rules() which returns a RuleIterator object with all the search rules in place for a specific index. Then using the save_rules() method to batch those rules into the other application's index.

However, when calling the save_rules() call a KeyError is thrown from a few indices. The output is as such:

Traceback (most recent call last):
  File "/Users/ryan.cambray/Documents/repos/algolia-clone/clone_rules.py", line 66, in <module>
    main()
  File "/Users/ryan.cambray/Documents/repos/algolia-clone/clone_rules.py", line 61, in main
    index_client.save_rules(rules=production_indices_rules[index],
  File "/opt/homebrew/lib/python3.9/site-packages/algoliasearch/search_index.py", line 393, in save_rules
    assert_object_id(rules)
  File "/opt/homebrew/lib/python3.9/site-packages/algoliasearch/helpers.py", line 45, in assert_object_id
    for obj in objects:
  File "/opt/homebrew/lib/python3.9/site-packages/algoliasearch/iterators.py", line 58, in __next__
    hit.pop("_highlightResult")
KeyError: '_highlightResult'

This is because in the iterators file there is no check on if the _highlightResult key is present, which in some rare cases from the data I've exported it is not. A quick fix would be to do an if here and check if its present before calling the pop method. I've been able to test this locally and adding this within the iterators.py file on line 58 enables the script to be run successfully:

                if ("_highlightResult" in hit):
                    hit.pop("_highlightResult")

Steps To Reproduce

shortcuts commented 1 year ago

hey, released in 2.6.3 https://pypi.org/project/algoliasearch/