Spring-data-elasticsearch Paging Query

Source: Internet
Author: User
Tags addall
	@Test public
	void Testquerypage () {
		QueryBuilder orderquery = Querybuilders.boolquery ()
				. Must ( Querybuilders.matchquery ("OrderType", "RO"));
		page<orderitem> page = Orderrepository.search (orderquery, Pagerequest.of (0, 1));
		SYSTEM.OUT.PRINTLN (page);

		page = Orderrepository.search (Orderquery, Pagerequest.of (1, 1));
		SYSTEM.OUT.PRINTLN (page);
	}
Appendix: 1, from the name can be seen, QueryBuilder is mainly used to build query conditions, filtering conditions, Sortbuilder mainly to build a sort. For example, we want to query everyone within 100 meters of a location and sort by distance:
	Double lat = 39.929986;  
	Double lon = 116.395645;  
  
        Long nowtime = System.currenttimemillis ();  
        Query a latitude of 100 meters within the range  
        of Geodistancequerybuilder builder = querybuilders.geodistancequery ("Address"). Point (Lat, lon)  
                . Distance (distanceunit.meters);  
  
        Geodistancesortbuilder Sortbuilder = sortbuilders.geodistancesort ("Address")  
                . Point (Lat, lon)  
                . Unit ( Distanceunit.meters)  
                . Order (SORTORDER.ASC);  
  
        pageable pageable = new Pagerequest (0, +);  
  
        Nativesearchquerybuilder builder1 = new Nativesearchquerybuilder (). Withfilter (builder). Withsort (Sortbuilder). Withpageable (pageable);  
	SearchQuery SearchQuery = Builder1.build ();  
2. limit Query result set size

Spring data allows developers to qualify the returned query result set size using the first and top keywords. FISRT and top need to follow a number representing the maximum size of the returned result set. If you do not follow a number, the returned result set size defaults to 1.

Example 8.Limiting of the result size of query with Top and first (result set size returned using the first and top limits)

User Findfirstbyorderbylastnameasc ();

User Findtopbyorderbyagedesc ();

Page<user> Queryfirst10bylastname (String LastName, pageable pageable);

Slice<user> Findtop3bylastname (String LastName, pageable pageable);

List<user> Findfirst10bylastname (String LastName, sort sort);

List<user> Findtop10bylastname (String LastName, pageable pageable);

Expressions that restrict the result set also support the DISTINCT keyword. Also, when the returned result set size is limited to 1 o'clock, Spring data supports wrapping the returned results to optional (Java 8 is new, which is a nullable container object.) If the value is present, the Ispresent () method returns True, and the call to the Get () method returns the object), as in the following example:

Optional<user> Findfirstbyorderbylastnameasc ();

You can also use first and top to limit the size of the result set in cases where queries are paged with page and slice.

Note that if you use the sort parameter to sort the results of a query and add a limit to the size of the result set, you can easily get the largest k elements or the smallest k elements.

3. using scan and scroll to process large result sets

The

Elasticsearch can use scan and scroll when working with large result sets. In spring Data elasticsearch, you can use Elasticsearchtemplate to work with scan and scroll to handle large result sets as follows.

@Test public void Shouldreturnresultswithscanandscrollforgivencriteriaquery () {//given list<  
        indexquery> entities = Createsampleentitieswithmessage ("Test message", 30);  
        When Elasticsearchtemplate.bulkindex (entities);  
        Elasticsearchtemplate.refresh (Sampleentity.class);  
        Then criteriaquery criteriaquery = new Criteriaquery (new Criteria ());  
        Criteriaquery.addindices (index_name);  
        Criteriaquery.addtypes (type_name);  
  
        Criteriaquery.setpageable (New Pagerequest (0, 10));  
        String scrollid = Elasticsearchtemplate.scan (Criteriaquery, +, false);  
        list<sampleentity> sampleentities = new arraylist<sampleentity> ();  
        Boolean hasrecords = true; while (hasrecords) {page<sampleentity> Page = Elasticsearchtemplate.scroll (Scrollid, 5000L, sampleent  
            Ity.class); if (Page.hascontent ()) {SamPleentities.addall (Page.getcontent ());  
            } else {hasrecords = false;  
        }} elasticsearchtemplate.clearscroll (Scrollid);  
    Assertthat (Sampleentities.size (), Is (Equalto (30)));   }
SearchQuery SearchQuery = new Nativesearchquerybuilder (). Withquery (Matchallquery ()). Withindices ("Test-index")
. Withtypes ("Test-type"). Withpageable (New Pagerequest (0,1)). Build ();
String scrollid = Elasticsearchtemplate.scan (Searchquery,1000,false);
list<sampleentity> sampleentities = new arraylist<sampleentity> ();
Boolean hasrecords = true; while (hasrecords) {page<sampleentity> Page = Elasticsearchtemplate.scroll (Scrollid, 5000L, new RESULTSMAPPER&L T
            Sampleentity> () {@Override public page<sampleentity> mapresults (searchresponse response) {
            list<sampleentity> chunk = new arraylist<sampleentity> ();
                    For (Searchhit searchHit:response.getHits ()) {if (Response.gethits (). Gethits (). length <= 0) {
                return null;
                } sampleentity user = new Sampleentity ();
                User.setid (Searchhit.getid ());User.setmessage (String) Searchhit.getsource (). Get ("message"));
            Chunk.add (user);
        } return new pageimpl<sampleentity> (chunk);
    }
    });
        if (page! = null) {Sampleentities.addall (page.getcontent ());
    Hasrecords = Page.hasnextpage ();
    } else{Hasrecords = false; }
    }
}



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.