django-es / django-elasticsearch-dsl

This is a package that allows indexing of django models in elasticsearch with elasticsearch-dsl-py.
Other
1.02k stars 262 forks source link

Search on NestedField Values Example #144

Open Miserlou opened 5 years ago

Miserlou commented 5 years ago

Hello! Thanks for this library!

I've read through your example application and the test suite, but I don't see any examples of how to perform a search/filter on the properties of a NestedField.

In your Car example, you call this Category - how would I find all of the Cars which belong to "Category 2"?

Thanks!

lexygon commented 5 years ago

Same here !

lexygon commented 5 years ago

I have been too lazy to being lazy :) So I found a way by checking the elasticsearch-dsl examples on the internet. Below you will see my working case. 'features' field is a many to many field.

@my_model.doc_type
class MyModelDocument(DocType):
    name = fields.TextField(
        analyzer=autocompleter,
    )

    features = fields.NestedField(properties={
        'name': fields.TextField(analyzer=autocompleter)
    })

    def get_queryset(self):
        return MyModel.objects.all().prefetch_related('features')

    class Meta:
        model = MyModel
        fields = []

result = MyModelDocument.search().query('nested', path='features', query=Q('term', features__name='kargo')).source(['features.name'])
anibalpacheco commented 1 year ago

Be careful when using nested fields, if the index is not yet created and you run the search_index management command with --populate, the mappings generated will be wrong and nested queries will not work (I spent 8 hours today to find this problem).

You should always use --rebuild or --create if the index is not yet created.

Note: the problem also happen for text fields mapped from integers without a proper prepare function defined.