django-elasticsearch-dsl-drf
django-elasticsearch-dsl-drf copied to clipboard
How to do query elastic search on multiple index
Questions
I'm working on global search which has to search on all the elastic search index and show the response. i'm referring this page for developing API . API ` class PaginatedElasticSearchAPIView(APIView, LimitOffsetPagination): serializer_class = None document_class = None @abc.abstractmethod def generate_q_expression(self, query): """This method should be overridden and return a Q() expression."""
def get(self, request, query): try: q = self.generate_q_expression(query) search = self.document_class.search().query(q) response = search.execute()
print(f'Found {response.hits.total.value} hit(s) for query: "{query}"')
results = self.paginate_queryset(response, request, view=self)
serializer = self.serializer_class(results, many=True)
return self.get_paginated_response(serializer.data)
except Exception as e: return HttpResponse(e, status=500) `
In views.py
` class SearchUsers(PaginatedElasticSearchAPIView): serializer_class = UserSerializer document_class = UserDocument
def generate_q_expression(self, query): return Q('bool', should=[ Q('match', username=query), Q('match', first_name=query), Q('match', last_name=query), ], minimum_should_match=1) class SearchCategories(PaginatedElasticSearchAPIView): serializer_class = CategorySerializer document_class = CategoryDocument
def generate_q_expression(self, query): return Q( 'multi_match', query=query, fields=[ 'name', 'description', ], fuzziness='auto') `
The elastic search document
`
blog/documents.py from django.contrib.auth.models import User from django_elasticsearch_dsl import Document, fields from django_elasticsearch_dsl.registries import registry
from blog.models import Category, Article
@registry.register_document class UserDocument(Document): class Index: name = 'users' settings = { 'number_of_shards': 1, 'number_of_replicas': 0, }
class Django: model = User fields = [ 'id', 'first_name', 'last_name', 'username', ] ` the above code queries only particular document class.
How to query on the multiple index and get the result similar to the below elastic search api call using django-ealsticsearch-dsl ?
In elastic search we have multi index query GET /user,categories/_search { "query": { "match": { "user.id": "kim" } } }
or
GET /*/_search { "query": { "match": { "user.id": "kim" } } }