mongoengine icon indicating copy to clipboard operation
mongoengine copied to clipboard

compare_indexes() breaks for text indexes due to sorting issue

Open der-joel opened this issue 3 years ago • 0 comments

Document.compare_index() breaks for text indexes if index definition and field definition are in different order. Minimal example:

from mongoengine import Document, StringField, connect, IntField

# connect to db "test" on local mongodb instance
db = connect()

# make sure db state does not influence example
db.drop_database("test")

class Working(Document):

    a = StringField()
    b = StringField()

    meta = {
        "indexes": [
            {
                "fields": [
                    "$a",
                    "$b"
                ]
            }
        ]
    }

class NotWorking(Document):

    a = StringField()
    b = StringField()

    meta = {
        "indexes": [
            {
                "fields": [
                    "$b",
                    "$a"
                ]
            }
        ]
    }

print(Working.compare_indexes())  # {'missing': [], 'extra': []}
print(NotWorking.compare_indexes())  # {'missing': [[('b', 'text'), ('a', 'text')]], 'extra': [[('a', 'text'), ('b', 'text')]]}

This happens because arrays are being compared instead of elements inside them. Snippet from Document.compare_indexes():

missing = [index for index in required if index not in existing]
extra = [index for index in existing if index not in required]

der-joel avatar Dec 30 '21 16:12 der-joel