spring-projects / spring-data-elasticsearch

Provide support to increase developer productivity in Java when using Elasticsearch. Uses familiar Spring concepts such as a template classes for core API usage and lightweight repository style data access.
https://spring.io/projects/spring-data-elasticsearch/
Apache License 2.0
2.92k stars 1.33k forks source link

There is an easier way to use elasticsearchTemplate and NativeQuery #2951

Closed Mrliuxu closed 2 months ago

Mrliuxu commented 3 months ago

This is my current code, which I find troublesome to use `List queries = new ArrayList<>(); if (StrUtil.isNotEmpty(params.getNodeNo())){ Query nodetermQuery = TermQuery.of(t -> t.field("nodeNo").value(params.getNodeNo()))._toQuery(); queries.add(nodetermQuery); } if (StrUtil.isNotEmpty(params.getParams())){ Query paramstermQuery = TermQuery.of(t -> t.field("params").value(params.getParams()))._toQuery(); queries.add(paramstermQuery);

    }
    if (ObjectUtil.isNotNull(params.getOptStDt()) && ObjectUtil.isNotNull(params.getOptEndDt())){
        Query optDtRangeQuery = RangeQuery.of(t -> t.field("optDt").gte(JsonData.of(params.getOptStDt())).lte(JsonData.of(params.getOptEndDt())))._toQuery();
        queries.add(optDtRangeQuery);

    }
    NativeQuery query = NativeQuery.builder()
            .withQuery(q->q.bool(m->m.must(queries)))
            .withPageable(pageable).build();
    SearchHits<GLogAc> searchHits = elasticsearchTemplate.search(query, GLogAc.class);`
sothawo commented 3 months ago

Not sure what your problem is. Can you explain by showing your GLogAc class and describing what you want to search?

Mrliuxu commented 3 months ago

yes,When I want to use elasticserach to achieve where similar to mysql where... and... The effect is when I need many conditions to query together. My current way is TermQuery, RangeQuery, etc., and then put these conditions into a set, and then use NativeQuery to conduct unified query. However, this operation will be troublesome when I have many conditions, so is there a simpler way to implement the query?

sothawo commented 3 months ago

The alternatives to using a NativeQuery are to either build a query using the criteria API or to build a StringQuery with the complete query to send to Elasticsearch. If none of these work for you, you will have to keep using the NativeQuery.