Elasticsearch5.0 Java Api(一) -- 插入索引

Elasticsearch5.X官方手册

Elasticsearch5.X官方手册中文版

Elasticsearch5.X Java Api官方手册

导入maven依赖

<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>transport</artifactId>
    <version>5.0.0</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>2.7</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.7</version>
</dependency>
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20160810</version>
</dependency>

索引内容

  假设我们要在ES中插入如下索引:

  index:flow

  type:data

  包含三个doc分别为time,inbyte,outbyte

创建包结构

  创建如下包结构,并在src/main/resources中创建log4j2.properties文件,写入以下内容:

appender.console.type = Console
appender.console.name = console
appender.console.layout.type = PatternLayout

rootLogger.level = info
rootLogger.appenderRef.console.ref = console

创建Flow实体

  在实体包下创建实体类

 1 package com.juyun.entity;
 2
 3 public class Flow {
 4
 5     private String time;
 6     private Integer inbyte;
 7     private Integer outbyte;
 8
 9     public Flow() {
10         super();
11     }
12
13     public Flow(String time, Integer inbyte, Integer outbyte) {
14         super();
15         this.time = time;
16         this.inbyte = inbyte;
17         this.outbyte = outbyte;
18     }
19
20     public String getTime() {
21         return time;
22     }
23
24     public void setTime(String time) {
25         this.time = time;
26     }
27
28     public Integer getInbyte() {
29         return inbyte;
30     }
31
32     public void setInbyte(Integer inbyte) {
33         this.inbyte = inbyte;
34     }
35
36     public Integer getOutbyte() {
37         return outbyte;
38     }
39
40     public void setOutbyte(Integer outbyte) {
41         this.outbyte = outbyte;
42     }
43
44 }

Flow.java

创建Json转换工具类

  在工具包下创建Java实体对象转json对象的方法

 1 package com.juyun.utils;
 2
 3 import java.io.IOException;
 4
 5 import org.elasticsearch.common.xcontent.XContentBuilder;
 6 import org.elasticsearch.common.xcontent.XContentFactory;
 7
 8 import com.juyun.entity.Flow;
 9
10 public class JsonUtil {
11
12     // Java实体对象转json对象
13     public static String model2Json(Flow flow) {
14         String jsonData = null;
15         try {
16             XContentBuilder jsonBuild = XContentFactory.jsonBuilder();
17             jsonBuild.startObject().field("time", flow.getTime()).field("inbyte", flow.getInbyte())
18                     .field("outbyte", flow.getOutbyte()).endObject();
19
20             jsonData = jsonBuild.string();
21             //System.out.println(jsonData);
22
23         } catch (IOException e) {
24             e.printStackTrace();
25         }
26         return jsonData;
27     }
28 }

JsonUtil

创建数据生成工厂类

  在工厂包下创建数据工厂类,生成数据集合

 1 package com.juyun.factory;
 2
 3 import java.text.SimpleDateFormat;
 4 import java.util.ArrayList;
 5 import java.util.Date;
 6 import java.util.List;
 7
 8 import com.juyun.entity.Flow;
 9 import com.juyun.utils.JsonUtil;
10
11 public class DataFactory {
12
13      public static DataFactory dataFactory = new DataFactory();
14
15         private DataFactory() {
16         }
17
18         public DataFactory getInstance() {
19             return dataFactory;
20         }
21
22         public static List<String> getInitJsonData() {
23
24             List<String> list = new ArrayList<String>();
25             String data1 = JsonUtil.model2Json(new Flow(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()).toString(),50,200));
26             String data2 = JsonUtil.model2Json(new Flow(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()).toString(),20,60));
27             list.add(data1);
28             list.add(data2);
29             return list;
30         }
31 }

DataFactory

插入索引

  前面都是数据准备工作,完成后,下面就开始使用elasticsearch提供的java api编写代码。我们将这部分代码都放在test包下。

  首先测试插入索引功能:

 1 package com.juyun.test;
 2
 3 import java.net.InetAddress;
 4 import java.util.List;
 5
 6 import org.elasticsearch.action.index.IndexResponse;
 7 import org.elasticsearch.client.transport.TransportClient;
 8 import org.elasticsearch.common.settings.Settings;
 9 import org.elasticsearch.common.transport.InetSocketTransportAddress;
10 import org.elasticsearch.transport.client.PreBuiltTransportClient;
11
12 import com.juyun.factory.DataFactory;
13
14 public class ElasticSearchHandler {
15
16     /**
17      * 测试插入索引的功能
18      * @param args
19      */
20     public static void main(String[] args) {
21
22         try {
23             // 设置集群名称
24             Settings settings = Settings.builder().put("cluster.name", "elasticsearch").build();
25             // 创建client
26             TransportClient client = new PreBuiltTransportClient(settings)
27                     .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("172.16.0.112"), 9300));
28
29             List<String> jsonData = DataFactory.getInitJsonData();
30
31             for (int i = 0; i < jsonData.size(); i++) {
32                 IndexResponse response = client.prepareIndex("flow", "data").setSource(jsonData.get(i)).get();
33                 System.out.println("成功创建了一个索引,索引名为:"+response.getIndex()+",类别为:"+response.getType()+",文档ID为:"+response.getId());
34             }
35
36             // 关闭client
37             client.close();
38
39         } catch (Exception e) {
40             e.printStackTrace();
41         }
42     }
43
44 }

ElasticSearchHandler.java

时间: 2024-10-27 14:12:33

Elasticsearch5.0 Java Api(一) -- 插入索引的相关文章

Elasticsearch5.0 Java Api(四) -- 检索索引

测试检索索引库的功能 1 package com.juyun.test; 2 3 import java.net.InetAddress; 4 5 import org.elasticsearch.client.Client; 6 import org.elasticsearch.common.settings.Settings; 7 import org.elasticsearch.common.transport.InetSocketTransportAddress; 8 import or

Elasticsearch5.0 Java Api(三) -- 删除索引

测试删除索引的功能 1 package com.juyun.test; 2 3 import java.net.InetAddress; 4 import java.net.UnknownHostException; 5 6 import org.elasticsearch.action.admin.indices.create.CreateIndexRequest; 7 import org.elasticsearch.action.admin.indices.create.CreateInd

Elasticsearch5.0 Java Api(六) -- 批量导入索引

将计算机本地的.json格式文件中的数据,批量导入到索引库中 1 package com.juyun.test; 2 3 import java.io.BufferedReader; 4 import java.io.File; 5 import java.io.FileNotFoundException; 6 import java.io.FileReader; 7 import java.io.IOException; 8 import java.net.InetAddress; 9 imp

Elasticsearch5.0 Java Api(五) -- 批量导出索引

从索引库中将检索到的数据导出到外部文件,文件格式为.json 1 package com.juyun.test; 2 3 import java.io.BufferedWriter; 4 import java.io.File; 5 import java.io.FileWriter; 6 import java.io.IOException; 7 import java.net.InetAddress; 8 import java.net.UnknownHostException; 9 10

Elasticsearch5.0 Java Api(二) -- 更新索引

elasticsearch提供了多种更新索引的方式,这里简单介绍其中五种 1 package com.juyun.test; 2 3 import java.io.IOException; 4 import java.net.InetAddress; 5 import java.util.concurrent.ExecutionException; 6 7 import org.elasticsearch.action.index.IndexRequest; 8 import org.elast

Elasticsearch5.0 Java Api(七) -- 聚合查询

测试聚合查询功能 1 package com.juyun.test; 2 3 import java.net.InetAddress; 4 import java.util.List; 5 6 import org.elasticsearch.action.search.SearchResponse; 7 import org.elasticsearch.client.Client; 8 import org.elasticsearch.common.settings.Settings; 9 i

Elasticsearch5.0 Java Api(八) -- 常用DSL查询

测试常用的DSL组合查询功能 1 package com.juyun.test; 2 3 import java.net.InetAddress; 4 5 import org.elasticsearch.action.search.SearchResponse; 6 import org.elasticsearch.client.Client; 7 import org.elasticsearch.common.settings.Settings; 8 import org.elasticse

elasticsearch-5.x JAVA API(002)

elasticsearch-5.x JAVA API 第二部分:集群健康与段合并 1. 集群健康 首先定义一个类来存储集群健康信息 package com.zw.elasticsearch.cluster; public class ClusterHealth { // 集群名 private String clusterName; // 集群中节点数目 private int number_of_node; // 活跃总分片数目 private int number_of_activeShar

ElasticSearch Java Api -创建索引

ElasticSearch JAVA API官网文档:https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/java-docs-index.html 一.生成JSON 创建索引的第一步是要把对象转换为JSON字符串.官网给出了四种创建JSON文档的方法: 1.1手写方式生成 String json = "{" + "\"user\":\"kimchy\"