How to Implement a Flexible Search Method in Java with Low Level Client to Filter, Sort, and Limit Fields?

Hello,

I'm working on implementing a search method in Java that needs to support several variations of search criteria. Specifically, I need the method to be able to:

  1. Search by a term within certain fields, conditionally filter the data by a date range, limit the output to only include specified fields, and sort the results by one or more fields.
  2. Perform the same operations as above but use a filterMap for filtering instead of a search term.
  3. Combine both term-based and filterMap-based filtering.

Here's the signature of the method I've come up with: private List<Map<String, Object>> search( final Set<String> requestedFields, final List<SortBy> sortByList, final List<String> termSearchableFields, final String searchTerm, final Map<String, Object> filterMap, final DateRangeTerm dateRangeTerm )...

This is what it boils down to: > GET patdocument-1382/_search

{
"query": {
"multi_match": {
"query": "Patient Letter-Lara",
"fields":["DocumentName","AuthorName"]
}
},
"fields": [
"DocumentName",
"AuthorName",
"CreatedDate"
],
"post_filter": {"range": { "CreatedDate.keyword": {"gte":"2022-10-04 23:44:37.000000","lte":"2023-06-24 05:46:49.000000"}}},
"sort" : [
{ "CreatedDate.keyword": {"order": "desc"}}],

"_source": false
}

This is the solution:

    String searchText = "xx";
    List fields = new ArrayList<>();
    fields.add("DocumentName");
    fields.add("AuthorName");

    List fieldsToReturn = new ArrayList<FieldAndFormat>();
   // list.add() ....
    double maxPricemaxPrice = 200.0;
    List sortOptions = new ArrayList<SortOptions>();
    RangeQuery range = RangeQuery.of(r -> r
            .field("price")
            .gte(JsonData.of(maxPricemaxPrice)) // <3>
    )._toQuery().range();
            try {
                SearchResponse<PatDocument2> response = client.search(s -> s
                                .index("patdocument-3482")
                                .query(q -> q
                                        .multiMatch(t -> t
                                                .fields(fields)
                                                .query(searchText)
                                        )
                                ).fields(fieldsToReturn)
                                .postFilter(r->r.range(range))
                                .sort(sortOptions),
                        PatDocument2.class);

It's not with the Low Level client then. May I suggest that you edit the title of your post?

I am using the low level Java client. What do you mean "it's not with the Low Level client"?

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.