algoliasearch-client-python icon indicating copy to clipboard operation
algoliasearch-client-python copied to clipboard

KeyError when batch saving rules from browse_rules()

Open ryancambray-ct opened this issue 3 years ago • 0 comments
trafficstars

  • Algolia Client Version: 2.6.1
  • Language Version: 3.9.9

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

  • Call browse_rules on an algolia search client from any initialised index
  • Batch save those rules into another index

ryancambray-ct avatar Jan 14 '22 16:01 ryancambray-ct