Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannot use FunctionScoreContainer? #1957

Closed
philbudne opened this issue Jan 4, 2025 · 2 comments · Fixed by #1960
Closed

Cannot use FunctionScoreContainer? #1957

philbudne opened this issue Jan 4, 2025 · 2 comments · Fixed by #1960
Assignees

Comments

@philbudne
Copy link

While trying to upgrade a project to version 8.17, existing code:

from elasticsearch_dsl import Search
from elasticsearch_dsl.function import RandomScore
from elasticsearch_dsl.query import FunctionScore

s = Search().query(
    FunctionScore(
        functions=[
            RandomScore()
        ]
    )
)

print(s.to_dict())

outputs:

{'query': {'function_score': {'functions': [{'random_score': {}}]}}}

But mypy complains:

test.py:9: error: Argument "functions" to "FunctionScore" has incompatible type "list[RandomScore]"; expected "Sequence[FunctionScoreContainer] | Sequence[dict[str, Any]] | DefaultType"  [arg-type]

mypy is happy with:

from elasticsearch_dsl import Search
from elasticsearch_dsl.function import RandomScore
from elasticsearch_dsl.query import FunctionScore
from elasticsearch_dsl.types import FunctionScoreContainer

s2 = Search().query(
    FunctionScore(
        functions=[
            FunctionScoreContainer(
                random_score=RandomScore()
            )
        ]
    )
)
print(s2.to_dict())

which fails at runtime with:

TypeError: unhashable type: 'FunctionScoreContainer'
@miguelgrinberg
Copy link
Collaborator

Thanks for raising this. The way FunctionScore is handled in this package is not exactly matching the Elasticsearch specification, so there are some customizations that need to be added. Unfortunately this extends to the typing, which I missed.

The correct code is your first option. The second option could be made to work, but it feels too verbose. I suggest you add a type ignore for now until I correct the type of the functions argument, which should be something like Sequence[ScoreFunction].

@philbudne
Copy link
Author

@miguelgrinberg Thanks for the quick response!

@miguelgrinberg miguelgrinberg self-assigned this Jan 7, 2025
miguelgrinberg added a commit to miguelgrinberg/elasticsearch-dsl-py that referenced this issue Jan 7, 2025
github-actions bot pushed a commit that referenced this issue Jan 7, 2025
miguelgrinberg added a commit that referenced this issue Jan 7, 2025
Fixes #1957

(cherry picked from commit 5d2bccd)

Co-authored-by: Miguel Grinberg <miguel.grinberg@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants