当前位置:   article > 正文

ElasticSearch 的增删改查_elasticsearch head 修改数据

elasticsearch head 修改数据

下面会记录对ElasticSearch 的详细使用方法进,内容包括索引的增删,数据的增删查

一 创建开发环境

首先需要安装es集群 这里使用的是7.17.8

二 当es能正常启动的时候,开始对es进行做操作

1.索引操作

   可以使用shell语法创建索引与删除索引,以及插入

  1. curl -X PUT "http://节点ip:9200/索引名称"
  2. curl -u 你的账号:你的密码 -XDELETE 'http://节点ip:9200/索引名称'
  3. curl -H "Content-Type: application/json" -XPUT 'http://note1:9200/index_test/doc/1' -d '{"age":128}'

   也可以所使用的java代码发送http请求

  1. import com.alibaba.fastjson.JSONObject;
  2. import org.apache.http.HttpEntity;
  3. import org.apache.http.HttpResponse;
  4. import org.apache.http.HttpStatus;
  5. import org.apache.http.client.config.RequestConfig;
  6. import org.apache.http.client.methods.CloseableHttpResponse;
  7. import org.apache.http.client.methods.HttpDelete;
  8. import org.apache.http.client.methods.HttpPost;
  9. import org.apache.http.client.methods.HttpPut;
  10. import org.apache.http.entity.StringEntity;
  11. import org.apache.http.impl.client.CloseableHttpClient;
  12. import org.apache.http.impl.client.HttpClientBuilder;
  13. import org.apache.http.impl.client.HttpClients;
  14. import org.apache.http.util.EntityUtils;
  15. import java.io.IOException;
  16. import java.util.Map;
  17. /* pom坐标
  18. <dependency>
  19. <groupId>org.elasticsearch</groupId>
  20. <artifactId>elasticsearch</artifactId>
  21. <version>7.17.8</version>
  22. </dependency>
  23. <dependency>
  24. <groupId>org.apache.httpcomponents</groupId>
  25. <artifactId>httpclient</artifactId>
  26. <version>4.5</version>
  27. </dependency>
  28. <dependency>
  29. <groupId>com.alibaba</groupId>
  30. <artifactId>fastjson</artifactId>
  31. <version>1.2.73</version>
  32. </dependency>
  33. */
  34. /**
  35. * 通过http对es进行索引的增删改
  36. */
  37. public class ESUtils {
  38. /**
  39. * 关闭资源
  40. *
  41. * @param client
  42. */
  43. public static void close(CloseableHttpClient client) {
  44. if (client != null) try {
  45. client.close();
  46. } catch (IOException e) {
  47. e.printStackTrace();
  48. }
  49. }
  50. public static void close(CloseableHttpResponse client) {
  51. if (client != null) try {
  52. client.close();
  53. } catch (IOException e) {
  54. e.printStackTrace();
  55. }
  56. }
  57. public static String sendDelete(String url, JSONObject headJson) throws Exception {
  58. String result = null;
  59. CloseableHttpClient client = null;
  60. try {
  61. client = HttpClientBuilder.create().build();
  62. HttpDelete put = new HttpDelete(url);
  63. if (headJson != null) {//设置请求头
  64. for (Map.Entry<String, Object> entry : headJson.entrySet()) {
  65. put.addHeader(entry.getKey(), String.valueOf(entry.getValue()));
  66. }
  67. }
  68. HttpResponse res = client.execute(put);
  69. if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
  70. result = EntityUtils.toString(res.getEntity());// 返回json格式:
  71. }
  72. } catch (Exception e) {
  73. throw new Exception(e);
  74. } finally {
  75. close(client);
  76. }
  77. return result;
  78. }
  79. public static String sendPost(String url, JSONObject headJson, String bodyJson) throws Exception {
  80. CloseableHttpClient client = null;
  81. String result = null;
  82. try {
  83. client = HttpClientBuilder.create().build();
  84. HttpPost post = new HttpPost(url);//支持get/post与put和delete - > HttpDelete
  85. if (headJson != null) {//设置请求头
  86. for (Map.Entry<String, Object> head : headJson.entrySet()) {
  87. post.addHeader(head.getKey(), head.getValue().toString());
  88. }
  89. }
  90. StringEntity body = new StringEntity(bodyJson, "utf-8");//设置请求体
  91. body.setContentEncoding("UTF-8");
  92. body.setContentType("application/json");//设置发送的请求体数据为json数据
  93. post.setEntity(body);
  94. HttpResponse res = client.execute(post);
  95. result = EntityUtils.toString(res.getEntity());// 返回json格式:
  96. } catch (Exception e) {
  97. throw new Exception(e);
  98. } finally {
  99. close(client);
  100. }
  101. return result;
  102. }
  103. public static String sendPut(String url, String jsonStr) {
  104. CloseableHttpClient httpClient = HttpClients.createDefault();
  105. HttpPut httpPut = new HttpPut(url);
  106. RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000).setConnectionRequestTimeout(35000).setSocketTimeout(60000).build();
  107. httpPut.setConfig(requestConfig);
  108. httpPut.setHeader("Content-type", "application/json");
  109. httpPut.setHeader("DataEncoding", "UTF-8");
  110. CloseableHttpResponse httpResponse = null;
  111. try {
  112. if (jsonStr != null) httpPut.setEntity(new StringEntity(jsonStr));
  113. httpResponse = httpClient.execute(httpPut);
  114. HttpEntity entity = httpResponse.getEntity();
  115. String result = EntityUtils.toString(entity);
  116. return result;
  117. } catch (Exception e) {
  118. e.printStackTrace();
  119. } finally {
  120. close(httpResponse);
  121. close(httpClient);
  122. }
  123. return null;
  124. }
  125. public static void main(String[] args) throws Exception {
  126. String respCreate = ESUtils.sendPut("http://note1:9200/index_test", null);//创建索引
  127. //映射最外层需要properties
  128. String mapping = "{\"properties\":{\"name\":{\"type\":\"text\",\"index\":true},\"sex\":{\"type\":\"text\",\"index\":false},\"age\":{\"type\":\"long\",\"index\":false}}}";
  129. String respUpdate = ESUtils.sendPut("http://note1:9200/index_test/doc/_mapping?include_type_name=true", mapping);//设置mapping映射
  130. String url = "http://note2:9200/index_test/doc?";//url后的路径表示: 索引/分类/id id的uri可以不要,即自动生成id
  131. String respInsert = sendPost(url, null, "{\"name\":\"张三123\",\"sex\":\"这是一段文本\",\"age\":128}");
  132. String respDelete = ESUtils.sendDelete("http://note1:9200/index_test", null);//删除索引
  133. System.out.println("respCreate创建索引响应: " + respCreate);
  134. System.out.println("respUpdate设置映射响应: " + respUpdate);
  135. System.out.println("respInsert插入数据响应: " + respInsert);
  136. System.out.println("respDelete删除索引响应: " + respDelete);
  137. }
  138. }

运行结果如下

 使用代码进行批处理入库

  1. import org.apache.http.HttpHost;
  2. import org.elasticsearch.action.bulk.BulkRequest;
  3. import org.elasticsearch.action.bulk.BulkResponse;
  4. import org.elasticsearch.action.index.IndexRequest;
  5. import org.elasticsearch.client.RequestOptions;
  6. import org.elasticsearch.client.RestClient;
  7. import org.elasticsearch.client.RestHighLevelClient;
  8. import java.io.IOException;
  9. import java.util.HashMap;
  10. import java.util.Map;
  11. import java.util.UUID;
  12. /*
  13. <dependency>
  14. <groupId>org.elasticsearch.client</groupId>
  15. <artifactId>elasticsearch-rest-high-level-client</artifactId>
  16. <version>7.17.7</version>
  17. <!-- 版本7.17.8有bug 使用7.17.7文件-->
  18. </dependency>
  19. */
  20. /**
  21. * 批处理
  22. */
  23. public class ESBatch {
  24. public static void main(String[] args) throws IOException {
  25. RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
  26. new HttpHost("note1", 9200),
  27. new HttpHost("note2", 9200),
  28. new HttpHost("note3", 9200)));
  29. BulkRequest bulkRequest = new BulkRequest();
  30. Map<String,Object> map = new HashMap();
  31. map.put("name", UUID.randomUUID().toString());
  32. bulkRequest.add(new IndexRequest().index("index_test").source(map));
  33. bulkRequest.add(new IndexRequest().index("index_test").source(map));
  34. bulkRequest.add(new IndexRequest().index("index_test").source(map));
  35. BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
  36. System.out.println("批量插,Took: " + bulkResponse.getTook());
  37. System.out.println("批量插入,Items: " + bulkResponse.getItems().length);
  38. client.close();
  39. }
  40. }

运行结果

 ​​​

 字段类型与映射数据说明

2.查询

`````````````````````````````

 2.获取操作elasticsearch的客户端

Settings settings = Settings.builder().put("cluster.name", "集群名称").build();
TransportClient client = new PreBuiltTransportClient(settings)
    .addTransportAddress(new TransportAddress(InetAddress.getByName("mini1"), 9300));
    .addTransportAddress(new TransportAddress(InetAddress.getByName("mini2"), 9300));
    .addTransportAddress(new TransportAddress(InetAddress.getByName("mini3"), 9300));

3.使用客户端client操作集群

    (1)导入数据

         处理数据

  1.     String json = "{\"key\":\"value\"}";
  2.     response = client.prepareIndex("索引名称", "类型", "id").setSource(json).get();

        批处理

           

  1.     String json = "{\"key\":\"value\"}"; //数据
  2.     IndexRequestBuilder indexRequestBuilder = client.prepareIndex("索引名称", "doc", "100").setSource(json);//创建请求
  3.     BulkRequestBuilder bulkRequestBuilder = client.prepareBulk();//批处理对象
  4.     bulkRequestBuilder.add(indexRequestBuilder);//添加到批处理
  5.     bulkRequestBuilder.add(indexRequestBuilder);
  6.     BulkResponse bulkItemResponses = bulkRequestBuilder.execute().actionGet();//执行处理获取结果集
  7.     BulkItemResponse[] items = bulkItemResponses.getItems();//获取每一条数据的处理结果

    (2)查询

        全文检索

  1.     QueryBuilder query = QueryBuilders.matchAllQuery();//查询类,查询全部
  2.     SearchResponse searchResponse = client.prepareSearch("索引").setTypes("类型").setQuery(query).execute().actionGet();//创建请求并获取结果
  3.     SearchHits hits = searchResponse.getHits();//获取数据集合
  4.     for (SearchHit sh:hits) {//遍历
  5.     System.out.println(sh.getSource());//获取单条数据
  6.     }

        搜索

  1.     QueryBuilder query = QueryBuilders.matchQuery("字段名","字段值").operator(Operator.OR);//过滤查询,查询固定值
  2.     ...

       多字段检索

 
   QueryBuilder query = QueryBuilders.multiMatchQuery("值","字段1","字段2");//同时指定多个field,不同field之间是或的关系

       多条件查询

  1.     QueryBuilder query1 = QueryBuilders.queryStringQuery("值1");//查询类1
  2.     QueryBuilder query2 = QueryBuilders.queryStringQuery("值2");//查询类2
  3.     SearchResponse searchResponse = client.prepareSearch("索引").setTypes("格式").setQuery(query1).setQuery(query2).get();//请求结果

       前缀查询

    QueryBuilder query = QueryBuilders.prefixQuery("字段", "值");

       通用匹配

    QueryBuilder query =  QueryBuilders.wildcardQuery("字段", "值.*");

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/68737
推荐阅读
相关标签
  

闽ICP备14008679号