赞
踩
现在java常用的有两种模式
Java TransportClient API 客户端
在 Elasticsearch 7 中已经说明该客户端将在 8.0 版本被废弃。
具体使用可参考 https://www.elastic.co/guide/en/elasticsearch/client/java-api/7.2/java-api.html
Java REST Client API 客户端
REST Client 有两个版本,一个是 Low Level,提供了比较简单的 HTTP 客户端功能。具体可参考 https://www.elastic.co/guide/en/elasticsearch/client/java-rest/7.2/java-rest-low.html
另一个是 High Level Client,基于 Low level Client,做了一些封装,比较好用。具体文档见
https://www.elastic.co/guide/en/elasticsearch/client/java-rest/7.2/java-rest-high.html
这里我们使用High Level Clien
为了测试加个springmvc,方便调用,其实也可以不加。
引用es的maven
<!--es客户端,不使用springboot封装的客户端 --> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> <version>7.5.2</version> </dependency> <dependency> <groupId>org.elasticsearch</groupId> <artifactId>elasticsearch</artifactId> <version>7.5.2</version> </dependency> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-client</artifactId> <version>7.6.2</version> </dependency> <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok --> <dependency>
加入json解析
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.28</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
配置文件改成yml
application.yml配置
server:
port: 8082
elasticsearch:
schema: http
address: 127.0.0.1:9200
connectTimeout: 5000
socketTimeout: 5000
connectionRequestTimeout: 5000
maxConnectNum: 100
maxConnectPerRoute: 100
EsApplication 记得加上扫描配置不然访问不到
package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; @ComponentScan(basePackages={"com.es.*"}) @SpringBootApplication public class EsApplication { public static void main(String[] args) { SpringApplication.run(EsApplication.class, args); } }
连接配置类
package com.es.tool; import org.apache.http.HttpHost; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestClientBuilder; import org.elasticsearch.client.RestHighLevelClient; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.ArrayList; import java.util.List; /** * @Deacription ElasticSearch 配置 * @Author x **/ @Configuration public class ElasticSearchConfiguration { /** 协议 */ @Value("${elasticsearch.schema:http}") private String schema; /** 集群地址,如果有多个用“,”隔开 */ @Value("${elasticsearch.address}") private String address; /** 连接超时时间 */ @Value("${elasticsearch.connectTimeout}") private int connectTimeout; /** Socket 连接超时时间 */ @Value("${elasticsearch.socketTimeout}") private int socketTimeout; /** 获取连接的超时时间 */ @Value("${elasticsearch.connectionRequestTimeout}") private int connectionRequestTimeout; /** 最大连接数 */ @Value("${elasticsearch.maxConnectNum}") private int maxConnectNum; /** 最大路由连接数 */ @Value("${elasticsearch.maxConnectPerRoute}") private int maxConnectPerRoute; @Bean(name = "restHighLevelClient") public RestHighLevelClient restHighLevelClient() { // 拆分地址 List<HttpHost> hostLists = new ArrayList<>(); String[] hostList = address.split(","); for (String addr : hostList) { String host = addr.split(":")[0]; String port = addr.split(":")[1]; hostLists.add(new HttpHost(host, Integer.parseInt(port), schema)); } // 转换成 HttpHost 数组 HttpHost[] httpHost = hostLists.toArray(new HttpHost[]{}); // 构建连接对象 RestClientBuilder builder = RestClient.builder(httpHost); // 异步连接延时配置 builder.setRequestConfigCallback(requestConfigBuilder -> { requestConfigBuilder.setConnectTimeout(connectTimeout); requestConfigBuilder.setSocketTimeout(socketTimeout); requestConfigBuilder.setConnectionRequestTimeout(connectionRequestTimeout); return requestConfigBuilder; }); // 异步连接数配置 builder.setHttpClientConfigCallback(httpClientBuilder -> { httpClientBuilder.setMaxConnTotal(maxConnectNum); httpClientBuilder.setMaxConnPerRoute(maxConnectPerRoute); return httpClientBuilder; }); return new RestHighLevelClient(builder); } }
es执行类
package com.es.tool; import com.alibaba.fastjson.JSON; import org.elasticsearch.action.delete.DeleteRequest; import org.elasticsearch.action.delete.DeleteResponse; import org.elasticsearch.action.get.GetRequest; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.action.update.UpdateRequest; import org.elasticsearch.action.update.UpdateResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.common.xcontent.XContentType; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.io.IOException; import java.util.Date; @Service public class IndexService { @Autowired private RestHighLevelClient restHighLevelClient; /** * 增加文档信息 */ public void addDocument() { try { // 创建索引请求对象 IndexRequest indexRequest = new IndexRequest("mydlq-user", "doc", "1"); UserInfo userInfo = new UserInfo(); userInfo.setUsername("赵六"); // 将对象转换为 byte 数组 byte[] json = JSON.toJSONBytes(userInfo); // 设置文档内容 indexRequest.source(json, XContentType.JSON); // 执行增加文档 IndexResponse response = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT); } catch (Exception e) { e.printStackTrace(); } } /** * 获取文档信息 */ public void getDocument() { try { // 获取请求对象 GetRequest getRequest = new GetRequest("mydlq-user", "_doc", "1"); // 获取文档信息 GetResponse getResponse = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT); // 将 JSON 转换成对象 if (getResponse.isExists()) { UserInfo userInfo = JSON.parseObject(getResponse.getSourceAsBytes(), UserInfo.class); System.out.println(userInfo); } } catch (IOException e) { } } /** * 更新文档信息 */ public void updateDocument() { try { // 创建索引请求对象 UpdateRequest updateRequest = new UpdateRequest("mydlq-user", "doc", "1"); // 设置员工更新信息 UserInfo userInfo = new UserInfo(); userInfo.setUsername("王五"); // 将对象转换为 byte 数组 byte[] json = JSON.toJSONBytes(userInfo); // 设置更新文档内容 updateRequest.doc(json, XContentType.JSON); // 执行更新文档 UpdateResponse response = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT); } catch (Exception e) { } } /** * 删除文档信息 */ public void deleteDocument() { try { // 创建删除请求对象 DeleteRequest deleteRequest = new DeleteRequest("mydlq-user", "doc", "1"); // 执行删除文档 DeleteResponse response = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT); } catch (IOException e) { } } }
对象类
package com.es.tool;
public class UserInfo {
public String username;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
控制层类
package com.es.controller; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.util.ResourceUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.es.tool.*; @RestController @RequestMapping("/all") public class AllController { @Autowired private IndexService IndexService; @RequestMapping("/getDocument") @ResponseBody public String getDocument(HttpServletRequest request, HttpSession session) { IndexService.getDocument(); return "0"; } @RequestMapping("/addDocument") @ResponseBody public String addDocument(HttpServletRequest request, HttpSession session) { IndexService.addDocument(); return "0"; } @RequestMapping("/updateDocument") @ResponseBody public String updateDocument(HttpServletRequest request, HttpSession session) { IndexService.getDocument(); return "0"; } @RequestMapping("/deleteDocument") @ResponseBody public String deleteDocument(HttpServletRequest request, HttpSession session) { IndexService.getDocument(); return "0"; } }
ie中打开 http://127.0.0.1:8082/all/addDocument
打开kibana中的开发工具执行
GET mydlq-user/_search
{
"query": {
"match_all": {}
}
}
已经写入 后续可以尝试增删改查
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。