Placing time limits on a query

The example application we have been working with has a limited set of test data, only a dozen apps, and a handful of devices. So, as long as your computer has a reasonable amount of processor and memory resources, the search queries should run almost instantaneously.

However, an application with real data might involve searching across millions of entities, and there may be a risk of your queries taking too long. As a matter of user experience if nothing else, you will probably want to limit the execution of your queries to some reasonable period of time.

Hibernate Search offers two approaches for time boxing a query. One is through the FullTextQuery object's limitExecutionTime method:

...
hibernateQuery.limitExecutionTimeTo(2, TimeUnit.SECONDS);
...

This method causes the query to gracefully halt after a specified period of time, and return all of the results that it had found up until that point. The first parameter is the number of time units, and the second parameter is the type of time unit (for example, microsecond, millisecond, second, and so on). The preceding code snippet will try to stop the query after two seconds of searching.

Tip

After this query runs, you can determine whether or not it was interrupted by calling the object's hasPartialResults() method. This Boolean method returns true if the query timed out before reaching its natural conclusion.

The second approach, using the setTimeout() method, is similar in concept and in the parameters taken:

...
hibernateQuery.setTimeout(2, TimeUnit.SECONDS);
...

However, this method is for situations where the search should fail completely upon timeout, rather than proceeding as if it didn't happen. The preceding query object will throw a QueryTimeoutException exception after running for two full seconds, and will not return any results that were found during that time.

Note

Be aware that with both of these approaches, Hibernate Search does the best it can to respect the specified period of time. It may actually take a bit more time for the query to halt.

Also, these timeout settings only affect Lucene access. Once your query has finished searching Lucene and starts pulling actual entities from the database, timeout control is in the hands of Hibernate ORM rather than Hibernate Search.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset