pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-elasticsearch</artifactId>
</dependency>
客户端配置
import lombok.Data;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;
@Configuration
@Data
public class ElasticsearchConfig extends AbstractElasticsearchConfiguration {
private String host="localhost";
private Integer port=9200;
@Override
public RestHighLevelClient elasticsearchClient() {
RestClientBuilder builder = RestClient.builder(new HttpHost(host,port));
RestHighLevelClient restHighLevelClient = new RestHighLevelClient(builder);
return restHighLevelClient;
}
}
dsl查询
import com.alibaba.fastjson.JSONObject;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.WrapperQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
@RestController
@RequestMapping("/es-client2")
public class EsClientController2 {
@Autowired
private RestHighLevelClient rstHighLevelClient;
@PostMapping("/query2")
public SearchResponse userEsClient(
@RequestBody JSONObject body
) throws IOException {
String index_name = body.getOrDefault("index_name", "").toString();
System.out.println("body:" + body);
String json = "{\"query\": {\"match\": {\"title\": \"hello world\"}}}";
//language=JSON5
String dsl = "{\n" +
" \"match_all\": {}\n" +
"}";
WrapperQueryBuilder queryBuilder = new WrapperQueryBuilder(dsl);
SearchRequest searchRequest = new SearchRequest();
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
// 设置分页
searchSourceBuilder.query(queryBuilder).from((int) 1).size((int) 10);
searchRequest.source(searchSourceBuilder).indices(index_name);
SearchResponse searchResp = rstHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
// 计算返回的条数
return searchResp;
}
}
结果
文章来源地址https://www.toymoban.com/news/detail-780367.html
文章来源:https://www.toymoban.com/news/detail-780367.html
到了这里,关于java直接使用dsl语句查询ES的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!