34-天亮大数据系列教程之ElasticSearch6系列最新版教程之java操作es-1

目录
1、java操作elasticsearch的方案选择与优缺点说明
2、客户端初始化操作
3、创建与删除索引
4、创建与删除类型
详情

1、java操作elasticsearch的可选方案与优缺点说明

  • TransportClient
    • 优点
      • 官方自带,历史最悠久
        • 作为ES集群的一个节点的角色存在,全部操作功能均支持。
      • 缺点
        • 内部请求需要做java序列化操作,而不是http restful请求操作,导致项目的可移值性较低。
        • 官方已逐渐放弃该方式,预计7.0及以后完全删除该方式。
    • es高级RestClient
      • 优点
        • 官方自带和强力推荐
        • 基于Http Restful请求,可移值性更高。
      • 缺点
        • 新推出不久,支持API不够全面,必要时候还要靠低级API。
    • JestClient
      • 优点
        • 第三方插件,最早期的Rest第三方插件。
        • 较成熟,社区和API都相对比较全面。
      • 缺点
        • API不如TransportClient全面,必要时候还需要面向官方自带的client api编程才行。
    • Spring Data Elasticsearch
      • 优点
        • 第三方插件,与spring生态集成度较高。
        • 各种与spring生态组件的结合均已支持,包括常用接口、注解等。
      • 缺点
        • 往往与spring绑定使用,使用范围有限。
        • 该项目要服从于spring团队的统一接口更新,往往更新不够快,会影响对elasticsearch新功能、新API的支持。
    • 我们的选择
      • TransportClient
        • 官方代表
        • 支持的API最全面,一个不漏。
      • JestClient
        • 第三方rest风格代表
        • restful风格,最老牌,简单易用。

2、客户端初始化操作

  • maven环境配置
    • pom.xml配置
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.tl.es</groupId>
  <artifactId>EsClient4Job001</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <!-- 首先配置仓库的服务器位置,首选阿里云,也可以配置镜像方式,效果雷同 -->
  <repositories>
   <repository>
     <id>nexus-aliyun</id>
     <name>Nexus aliyun</name>
     <url>http://maven.aliyun.com/nexus/content/groups/public</url>
   </repository>
  </repositories>
  <dependencies>
   <dependency>
     <groupId>org.elasticsearch.client</groupId>
     <artifactId>transport</artifactId>
     <version>6.3.1</version>
   </dependency>
   <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
   <dependency>
     <groupId>org.apache.logging.log4j</groupId>
     <artifactId>log4j-core</artifactId>
     <version>2.7</version>
   </dependency>


        <!-- log -->
        <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.25</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.25</version>
            <!-- <scope>test</scope> -->
        </dependency>
   <dependency>
     <groupId>io.searchbox</groupId>
     <artifactId>jest</artifactId>
     <version>6.3.0</version>
   </dependency>
  </dependencies>
  <build>
   <finalName>EsClient4Job001</finalName>
   <plugins>
     <plugin>
       <artifactId>maven-assembly-plugin</artifactId>
       <configuration>
        <descriptorRefs>
          <descriptorRef>jar-with-dependencies</descriptorRef>
        </descriptorRefs>
       </configuration>
       <executions>
        <execution>
          <id>make-assembly</id>
          <phase>package</phase>
          <goals>
            <goal>assembly</goal>
          </goals>
        </execution>
       </executions>
     </plugin>
     <plugin>
       <artifactId>maven-compiler-plugin</artifactId>
       <version>2.3.2</version>
       <configuration>
        <source>1.8</source>
        <target>1.8</target>
        <encoding>UTF-8</encoding>
       </configuration>
     </plugin>
   </plugins>
  </build>
</project>
  • 配置文件依赖
    • log4j.properties
      • log4j2.properties
      • 特别说明
        • 如果直接写在测试包下,则把这两个配置文件放到src/test/resources
        • 如果直接写在正式工程包下,则把这两个配置文件放到src/main/resources
  • TransportClient
package com.tl.test;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;
import java.util.concurrent.ExecutionException;

import org.elasticsearch.action.ActionFuture;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

public class TestESTransportClient {
    // 声明一个client变量
    public TransportClient client = null;

    public TestESTransportClient() throws UnknownHostException {
        init();
    }

    // 初始化TransportClient
    public void init() throws UnknownHostException {
        /**
         * 配置相关参数, 包括集群名称:标识链接哪个es集群 是否开启嗅探其它集群群服务节点的能力,使新增或移除的集群节点自动感知到
         * 其嗅探功能使用效果并不理想,还是以直接显式添加服务节点
         */
        Settings settings = Settings.builder()
                .put("cluster.name", "tianliangedu_es_cluster")
                .put("client.transport.sniff", true).build();
        // 将参数应用到某个client对象中
        client = new PreBuiltTransportClient(settings);
        // 显式添加响应es集群操作的节点机器,注意是9300管理端口
        client.addTransportAddress(new TransportAddress(InetAddress
                .getByName("DESKTOP-0BUQ2LS"), 9300));
    }

    public static void main(String[] args) throws InterruptedException,
            ExecutionException, UnknownHostException {
        // 初始化client工具类
        TestESTransportClient transportClient = new TestESTransportClient();
        System.out.println(transportClient.client);
    }
}
  • JestClient
package com.tl.test;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestClientFactory;
import io.searchbox.client.config.HttpClientConfig;
import com.google.gson.GsonBuilder;
public class TestJest {
  //声明一个JestClient的工厂对象,后续通过它持续不断的产出jest client对象
  JestClientFactory factory = null;
  //构造方法,初始化工厂对象
  public TestJest(String esURL) {
    // 初始化jestclient工厂对象
    factory = new JestClientFactory();
    // 初始工厂的配置参数
    factory.setHttpClientConfig(new HttpClientConfig.Builder(esURL)
         .gson(new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss")
             .create()).multiThreaded(true).readTimeout(10000)
         .build());
  }
  /**
   * 定义一个获取RestClient的client对象的静态方法
   * 传入指定的任意es集群节点的数据服务url即可,如http://localhost:9200等 注意是9200数据服务端口
   *
   * @param esUrl
   * @return
   */
  public JestClient getClient() {
    // 在工厂中拿到一个对象
    return factory.getObject();
  }
  public static void main(String[] args) {
    String esURL = "http://localhost:9200";
    TestJest testJest = new TestJest(esURL);
    JestClient jestClient = testJest.getClient();
    System.out.println(jestClient);
  }
}

3、创建与删除索引

  • TransportClient
// 创建索引,传入索引名称
  public void createIndex(String indexName) {
    client.admin().indices().prepareCreate(indexName).execute().actionGet();
  }
  // 删除索引,传入索引名称
  public void deleteIndex(String indexName) {
    client.admin().indices().prepareDelete(indexName).execute().actionGet();
  }
  public static void main(String[] args) throws InterruptedException,
       ExecutionException, UnknownHostException {
    // 初始化client工具类
    TestESTransportClient transportClient = new TestESTransportClient();
    // 调用创建索引方法
    String indexName="index_from_tc";
    transportClient.createIndex(indexName);
    transportClient.deleteIndex(indexName);

    System.out.println("done");
  }
  • JestClient
// 创建索引,指定索引名称
  public void createIndex(String indexName) throws IOException {
    CreateIndex createIndex = new CreateIndex.Builder(indexName).build();
    this.getClient().execute(createIndex);
  }
  // 删除索引,指定索引名称
  public void deleteIndex(String indexName) throws IOException {
    DeleteIndex createIndex = new DeleteIndex.Builder(indexName).build();
    this.getClient().execute(createIndex);
  }
  public static void main(String[] args) throws IOException {
    String esURL = "http://localhost:9200";
    TestJest testJest = new TestJest(esURL);
    String indexName = "index_from_jest";
    testJest.createIndex(indexName);
    testJest.deleteIndex(indexName);
    System.out.println("done");
  }

4、创建与删除类型

  • 关于删除类型的说明

    • 由于es6.x版本改成index:type的1:1形式,删除类型直接采用删除索引的API即可。

      • TransportClient
// 创建一个空的类型,传入索引名称和类型,该索引名必须已存在
  public void createType(String indexName, String typeName)
       throws IOException {
    XContentBuilder contentBuilder = XContentFactory.jsonBuilder()
         .startObject().startObject("properties").startObject("title")
         .field("type", "text").field("analyzer", "index_ansj")
         .field("search_analyzer", "query_ansj").endObject()
         .startObject("source_url").field("type", "keyword").endObject()
         .startObject("post_time").field("type", "date")
         .field("format", "yyyy-MM-dd HH:mm:ss").endObject()
         .startObject("insert_time").field("type", "date")
         .field("format", "yyyy-MM-dd HH:mm:ss").endObject().endObject()
         .endObject();
    PutMappingRequest putMappingRequest = Requests
         .putMappingRequest(indexName).type(typeName)
         .source(contentBuilder);
    this.client.admin().indices().putMapping(putMappingRequest).actionGet();
  }
  public static void main(String[] args) throws InterruptedException,
       ExecutionException, IOException {
    // 初始化client工具类
    TestESTransportClient transportClient = new TestESTransportClient();
    // 调用创建索引方法
    String indexName = "index_from_tc";
    String typeName = "type_from_tc";
    transportClient.createIndex(indexName);
    // transportClient.deleteIndex(indexName);
    transportClient.createType(indexName, typeName);
    System.out.println("done");
  }
  • JestClient
// 创建索引的类型,该索引必须存在
  public boolean createType(String indexName, String typeName)
       throws IOException {
    String source = "{\""
         + typeName
         + "\":{\"properties\":{"
         + "\"title\":{\"type\":\"text\",\"analyzer\":\"index_ansj\",\"search_analyzer\":\"query_ansj\"}"
         + ",\"source_url\":{\"type\":\"keyword\"}"
         + ",\"post_time\":{\"type\":\"date\",\"format\":\"yyyy-MM-dd HH:mm:ss\"}"
         + ",\"insert_time\":{\"type\":\"date\",\"format\":\"yyyy-MM-dd HH:mm:ss\"}"
         + "}}}";
    PutMapping putMapping = new PutMapping.Builder(indexName, typeName,
         source).build();
    JestResult jr = this.getClient().execute(putMapping);
    return jr.isSucceeded();
  }
  public static void main(String[] args) throws IOException {
    String esURL = "http://localhost:9200";
    TestJest testJest = new TestJest(esURL);
    String indexName = "index_from_jest";
    String typeName = "type_from_jest";
    testJest.createIndex(indexName);
    System.out.println(testJest.createType(indexName, typeName));
    System.out.println("done");
  }


天亮教育是一家从事大数据云计算、人工智能、教育培训、产品开发、咨询服务、人才优选为一体的综合型互联网科技公司。
公司由一批BAT等一线互联网IT精英人士创建,
以”快乐工作,认真生活,打造高端职业技能教育的一面旗帜”为愿景,胸怀”让天下没有难找的工作”使命,
坚持”客户第一、诚信、激情、拥抱变化”的价值观,
全心全意为学员赋能提效,践行技术改变命运的初心。

更多学习讨论, 请加入
官方-天亮大数据交流-366784928
群二维码:
这里写图片描述
天亮教育公开课-从小白到大佬修成记-全系列视频地址:http://bbs.myhope365.com/forum.php?mod=viewthread&tid=1422&extra=page%3D1

欢迎关注天亮教育公众号,大数据技术资料与课程、招生就业动态、教育资讯动态、创业历程分享一站式分享,官方微信公众号二维码:
这里写图片描述

天亮教育官方群318971238,
爬虫、nlp技术qq群320349384
hadoop & spark & hive技术群297585251,
官网:http://myhope365.com
官方天亮论坛:http://bbs.myhope365.com/

猜你喜欢

转载自blog.csdn.net/erliang20088/article/details/81663410