Haystack and Elasticsearch: Limit Number of Results

I have 2 servers with Haystack:

  • Server 1 . It has elasticsearch installed.
  • Server2 . This object does not have elasticsearch, requests are made in Server1

My problem is pagination when I make requests from Server2 to Server1 :

  • Server2 makes a request to Server1
  • Server1 send all results back to Server2
  • Server2 does pagination

But this is not optimal, if the query returns 10,000 objects, the query will be slow.

I know that you can send elasticsearch some values ​​in the request ( size , from and to ), but I do not know if it is possible using Haystack , I checked the documentation and looked for it and did not find anything.

  • How can I set up an inquiry to Haystack to obtain the results 10 to 10?

Edit

  • Is it possible that if I do SearchQuerySet()[10000:10010] , it will only query 10 items?
  • Or will he query all the elements and then filter them?

Edit2

I found this in Haystack Docs:

The function seems to do what I'm trying to do:

Limits the query by changing either the start, end, or both offsets.

And then I tried to do:

 from haystack.query import SearchQuerySet sqs = SearchQuerySet() sqs.query.set_limits(low=0, high=4) sqs.filter(content='anything') 

The result is a complete list, for example, I never add the set_limit line

  • Why does not it work?
+5
source share
2 answers

The sandwich works as distinct from Django ORM. After limiting the set of queries, you must call get_results () to get limited results. This is really smart because it avoids multiple requests from Elastic.

Example:

 # Assume you have 800 records. sqs = SearchQuerySet() sqs.query.set_limits(low=0, high=4) len(sqs) # Will return 800 records len(sqs.get_results()) # Will return first 4 records. 

Hope this helps.

+3
source

Adding Yigit to the answer if you want these offsets in the filtered records to simply add a filter condition when you form a SearchQuerySet .

Also remember, once limits are set, you cannot change them by setting them again. You will need to form SearchQuerySet() again, or there is a way to remove the restrictions.

 results = SearchQuerySet().filter(content="keyword") #we have a filtered resultSet now let find specific records results.query.set_limits(0,4) return results.query.get_results() 
-1
source

Source: https://habr.com/ru/post/1210393/


All Articles