赞
踩
Elasticsearch 使用的是标准的 RESTful 风格的 API 和 JSON。此外,还构建和维护了很多其他语言的客户端,例如 Java、Python、.NET、SQL 和 PHP。
本章节通过整合Java客户端,实现对 Elasticsearch服务进行访问。
这里使用IDEA创建项目
elasticsearch依赖
<properties>
<java.version>1.8</java.version>
<!-- 统一版本 -->
<elasticsearch.version>7.9.3</elasticsearch.version>
</properties>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
fastjson、lombok依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.70</version>
</dependency>
<!-- lombok需要安装插件 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
1.es没有密码配置
@Configuration
public class ElasticSearchConfig {
// 注册 rest高级客户端
@Bean
public RestHighLevelClient restHighLevelClient(){
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("127.0.0.1",9200,"http")
)
);
return client;
}
}
2.带密码(es设置密码情况下,需配置)
@Configuration
public class ElasticSearchConfig {
// 注册 rest高级客户端
@Bean
public RestHighLevelClient restHighLevelClient(){
HttpHost host=new HttpHost("10.7.71.112", 9200, HttpHost.DEFAULT_SCHEME_NAME);
RestClientBuilder builder=RestClient.builder(host);
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic", "gree@2020"));
builder.setHttpClientConfigCallback(f -> f.setDefaultCredentialsProvider(credentialsProvider));
RestHighLevelClient restClient = new RestHighLevelClient( builder);
return restClient;
}
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User implements Serializable {
private String name;
private Integer age;
}
package com.gree.esdemo7; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.client.indices.CreateIndexRequest; import org.elasticsearch.client.indices.CreateIndexResponse; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.io.IOException; @SpringBootTest class EsDemo7ApplicationTests { @Autowired public RestHighLevelClient restHighLevelClient; @Test void contextLoads() { } //创建索引 @Test public void testCreateIndex() throws IOException{ CreateIndexRequest request = new CreateIndexRequest("user_index"); CreateIndexResponse response = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT); System.out.println(response.isAcknowledged()); System.out.println(response); restHighLevelClient.close(); } }
1、创建 SearchRequest搜索请求
创建 SearchRequest 搜索请求,如果不带参数,表示查询所有索引2、创建 SearchSourceBuilder条件构造
创建 SearchSourceBuilder条件构造,构建搜索的条件。
添加大部分查询参数到 SearchSourceBuilder,还可以接收 QueryBuilders构建的查询参数。3、将 SearchSourceBuilder 添加到 SearchRequest中
4、执行查询
5、解析查询结果
示例:
这里打印出来的查询语句,为json格式,即RestFul API接口执行语句
示例1
public List<String> getPageDocumentsByIndex(String index, int pageNum, int pageSize) { try { SearchRequest searchRequest = new SearchRequest(index); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); // 查询索引下所有的文档 sourceBuilder.query(QueryBuilders.matchAllQuery()); //计算出记录起始下标 int from = (pageNum - 1) * pageSize; // 起始记录下标,从0开始 sourceBuilder.from(from); //每页显示的记录数 sourceBuilder.size(pageSize); searchRequest.source(sourceBuilder); SearchResponse response = esClient.search(searchRequest, RequestOptions.DEFAULT); SearchHits searchHits = response.getHits(); List<String> result = new ArrayList<>(); searchHits.forEach(searchHit -> result.add(searchHit.getSourceAsString())); return result; } catch (Exception e) { log.error("查询索引[{}]的文档失败", index, e); throw new MyException("查询索引[" + index + "]的文档失败"); } }
示例2
@RestController @RequestMapping("/es") public class SearchController { @Autowired private RestHighLevelClient restHighLevelClient; @PostMapping("/article/{keyWords}") public List<Map<String,Object>> articleSearch(@PathVariable("keyWords") String keyWords) throws IOException { //通过关键词查询相应文章,返会id,标题,相应内容 SearchRequest searchRequest = new SearchRequest("article"); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); //设置高亮 //searchSourceBuilder.highlighter(new HighlightBuilder()); //System.out.println(key); TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("content", keyWords); searchSourceBuilder.query(termQueryBuilder); searchRequest.source(searchSourceBuilder); SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT); SearchHits hits = response.getHits(); Long totalHits = hits.getTotalHits().value; System.out.println("查询的结果条数:"+totalHits); List<Map<String,Object>> results=new ArrayList<>(); for (SearchHit documentFields : hits) { System.out.println(documentFields.getSourceAsString()); results.add(documentFields.getSourceAsMap()); } return results; } }
转换成对象输出
@RestController @RequestMapping("/es") public class SearchController { @Autowired private RestHighLevelClient restHighLevelClient; @GetMapping("/article/{keyWords}") public List<ArticleDO> articleSearch(@PathVariable("keyWords") String keyWords) throws IOException { //通过关键词查询相应文章,返会id,标题,相应内容 SearchRequest searchRequest = new SearchRequest("article"); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); //设置高亮 HighlightBuilder highlightBuilder = new HighlightBuilder(); highlightBuilder.preTags("<font color='red'>"); highlightBuilder.postTags("</font>"); highlightBuilder.field("content"); searchSourceBuilder.highlighter(highlightBuilder); TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("content", keyWords); searchSourceBuilder.query(termQueryBuilder); searchRequest.source(searchSourceBuilder); SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT); SearchHits hits = response.getHits(); Long totalHits = hits.getTotalHits().value; System.out.println("查询的结果条数:"+totalHits); //遍历结果 List<Map<String,Object>> results=new ArrayList<>(); for (SearchHit documentFields : hits) { System.out.println(documentFields.getSourceAsString()); results.add(documentFields.getSourceAsMap()); } //listmap转换为list对象 List<ArticleDO> list = JSON.parseArray(JSONArray.toJSONString(results), ArticleDO.class); return list; } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。