Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How add sorting to spring data elasticsearch

I m writing an api using elasticsearch spring data and I want to add ordering.I cant find a resolve in google. So I write here to ask you guys how I can do that. If you will need more code please tell me what u need and I try to add more code.

My code looks like:

AuctionQueryController.java

@RequestMapping(value = "/auctions/search", produces = MediaType.APPLICATION_JSON_VALUE)
    private List<Auction> search(
            @RequestParam(value = "categoryId", required = false) Long categoryId,
            @RequestParam(value = "treeCategoryId", required = false) Long treeCategoryId,
            @RequestParam(value = "currency", required = false) String currency,
            @RequestParam(value = "priceFrom", required = false) Long priceFrom,
            @RequestParam(value = "priceTo", required = false) Long priceTo,
            @RequestParam(value = "startDateFrom", required = false) Long startDateFrom,
            @RequestParam(value = "startDateTo", required = false) Long startDateTo,
            @RequestParam(value = "endDateFrom", required = false) Long endDateFrom,
            @RequestParam(value = "endDateTo", required = false) Long endDateTo,
            @RequestParam(value = "title", required = false) String title,
            @RequestParam(value = "uid", required = false) Long uid,
            Pageable pageable) {

        final AuctionIndexSearchParams searchParams = AuctionIndexSearchParams.builder()
                .categoryId(categoryId)
                .treeCategoryId(treeCategoryId)
                .currency(currency)
                .priceFrom(priceFrom)
                .priceTo(priceTo)
                .startDateFrom(startDateFrom)
                .startDateTo(startDateTo)
                .endDateFrom(endDateFrom)
                .endDateTo(endDateTo)
                .title(title)
                .uid(uid)
                .build();

        return auctionService.searchByIndexParams(searchParams, pageable);
    }

AuctionService.java

public List<Auction> searchByIndexParams(AuctionIndexSearchParams searchParams, Pageable pageable) {
        final List<FilterBuilder> filters = Lists.newArrayList();
        final NativeSearchQueryBuilder searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery());

        Optional.ofNullable(searchParams.getCategoryId()).ifPresent(v -> filters.add(boolFilter().must(termFilter("cat", v))));
        Optional.ofNullable(searchParams.getCurrency()).ifPresent(v -> filters.add(boolFilter().must(termFilter("curr", v))));
        Optional.ofNullable(searchParams.getTreeCategoryId()).ifPresent(v -> filters.add(boolFilter().must(termFilter("tcat", v))));
        Optional.ofNullable(searchParams.getUid()).ifPresent(v -> filters.add(boolFilter().must(termFilter("uid", v))));

       final BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();

        if (Optional.ofNullable(searchParams.getTitle()).isPresent()) {
            boolQueryBuilder.should(queryStringQuery(searchParams.getTitle()).analyzeWildcard(true).field("title"));
        }

        if (Optional.ofNullable(searchParams.getStartDateFrom()).isPresent()
                && Optional.ofNullable(searchParams.getStartDateTo()).isPresent()) {
            filters.add(rangeFilter("start_date").from(searchParams.getStartDateFrom()).to(searchParams.getStartDateTo()));
        }

        if (Optional.ofNullable(searchParams.getEndDateFrom()).isPresent()
                && Optional.ofNullable(searchParams.getEndDateTo()).isPresent()) {
            filters.add(rangeFilter("end_date").from(searchParams.getEndDateFrom()).to(searchParams.getEndDateTo()));
        }

        if (Optional.ofNullable(searchParams.getPriceFrom()).isPresent()
                && Optional.ofNullable(searchParams.getPriceTo()).isPresent()) {
            filters.add(rangeFilter("price").from(searchParams.getPriceFrom()).to(searchParams.getPriceTo()));
        }

        searchQuery.withPageable(pageable);
        searchQuery.withQuery(boolQueryBuilder);
        FilterBuilder[] filterArr = new FilterBuilder[filters.size()];
        filterArr = filters.toArray(filterArr);
        searchQuery.withFilter(andFilter(filterArr));

        final FacetedPage<AuctionIndex> search = auctionIndexRepository.search(searchQuery.build());

        return search.map(index ->
                        auctionRepository.findAuctionById(Long.valueOf(index.getId()))
        ).getContent();
    }
like image 508
rad11 Avatar asked Feb 10 '16 08:02

rad11


People also ask

How do I add sorting in spring boot?

In Spring Data JPA query results can be sorted in two ways: using an ORDER BY clause in a JPQL query. adding a parameter of type Sort to the query method.

Does spring data support Elasticsearch?

The Spring Data Elasticsearch project provides integration with the Elasticsearch search engine. Key functional areas of Spring Data Elasticsearch are a POJO centric model for interacting with a Elastichsearch Documents and easily writing a Repository style data access layer.

What is the default sort order in Elasticsearch?

In Elasticsearch, the relevance score is represented by the floating-point number returned in the search results as the _score, so the default sort order is _score descending.


1 Answers

You can use SortBuilders for this.

        searchQuery.withSort(SortBuilders.fieldSort("fieldName").order(SortOrder.DESC))

This will sort your result on the basis of fieldName passed.

Hope this helps

like image 120
Richa Avatar answered Oct 15 '22 08:10

Richa