ES javaAPI操作

1.将Centos7集群都启动  

2.将Centos的插件打开

head插件是一个用来浏览、与ES数据进行交互的web前端展示插件,是一个用来监视ES状态的客户端插件。

3.添加日志

添加log4j2.xml        https://www.cnblogs.com/JBLi/p/11403956.html

 

4.添加依赖

 <dependencies>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>5.4.3</version>
        </dependency>

        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>transport</artifactId>
            <version>5.4.3</version>
        </dependency>

        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.9.0</version>
        </dependency>

        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>4.1.25.Final</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

 

 

代码如下

package com.bw.es;

import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.get.MultiGetItemResponse;
import org.elasticsearch.action.get.MultiGetRequest;
import org.elasticsearch.action.get.MultiGetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.Requests;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.Iterator;

public class TestES {
    private TransportClient client;
    @Before
    public void getClient() throws Exception {

        // 1 设置连接的集群名称
        Settings settings = Settings.builder().put("cluster.name", "my-cluster").build();

        // 2 连接集群
        client = new PreBuiltTransportClient(settings);
        client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.137.10"), 9300));
        // 3 打印集群名称
        System.out.println(client.toString());

       // client.close();
    }

    //创建索引
    @Test
    public void createIndex_blog(){
        // 1 创建索引
        client.admin().indices().prepareCreate("blog4").get();
        // 2 关闭连接
        client.close();
    }

    //删除索引
    @Test
    public void deleteIndex() {
       //删除索引
        client.admin().indices().prepareDelete("hadoop2").get();
        //关闭资源
        client.close();
    }
    //创建文档以json形式
    @Test
    public void createIndexbyJson(){
        //创建文档的内容
        String json = "{" + "\"id\":\"1\"," + "\"title\":\"基于Lucene的搜索服务器\","
                + "\"content\":\"它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口\"" + "}";

        //创建
        IndexResponse re = client.prepareIndex("blog", "article", "1").setSource(json).execute().actionGet();
        //打印返回值
        System.out.println("索引="+re.getIndex());
        System.out.println("类型="+re.getType());
        System.out.println("id="+re.getId());
        System.out.println("版本号="+re.getVersion());
        System.out.println("结果="+re.getResult());
        client.close();
    }

    //创建文档以hashmap
    @Test
    public void createIndexByMap(){
        HashMap<String, Object> json = new HashMap<String, Object>();

        json.put("id","2");
        json.put("title","建总");
        json.put("content","看片。拍片");

        IndexResponse re = client.prepareIndex("blog", "article", "2").setSource(json).execute().actionGet();
        //打印返回值
        System.out.println("索引="+re.getIndex());
        System.out.println("类型="+re.getType());
        System.out.println("id="+re.getId());
        System.out.println("版本号="+re.getVersion());
        System.out.println("结果="+re.getResult());
        client.close();
    }

    //创建文档以builder

    @Test
    public void createIndexByBuilder() throws IOException{
        XContentBuilder b= XContentFactory.jsonBuilder()
                .startObject()
                .field("id", "4")
                .field("title", "伟哥")
                .field("content", "买药吃药")
                .endObject();
        IndexResponse re = client.prepareIndex("blog", "article", "3").setSource(b).execute().actionGet();
        //打印返回值
        System.out.println("索引="+re.getIndex());
        System.out.println("类型="+re.getType());
        System.out.println("id="+re.getId());
        System.out.println("版本号="+re.getVersion());
        System.out.println("结果="+re.getResult());
        client.close();
    }

    //单个索引查询
    @Test
    public void queryIndex(){
        //查询
        GetResponse re = client.prepareGet("blog", "article", "3").get();
        //打印
        System.out.println(re.getSourceAsString());
        //关闭资源
        client.close();
    }

    //多个索引查询
    @Test
    public void queryMultiIndex(){
        //查询
        MultiGetResponse re = client.prepareMultiGet().add("blog", "article", "3")
                .add("blog", "article", "2", "3")
                .add("blog", "article", "1").get();
        for(MultiGetItemResponse mu:re){
            GetResponse re1 = mu.getResponse();
            //判断是否存在
            if(re1.isExists()){
                System.out.println(re1.getSourceAsString());
            }
        }
    }

    //更新文档数据update
    @Test
    public void update() throws Exception{
        UpdateRequest up = new UpdateRequest("blog", "article", "2");
        up.doc(XContentFactory.jsonBuilder().startObject()
        .field("id","2")
        .field("title","建总你好")
        .field("content","看片 拍片 西片")
        .endObject());
        UpdateResponse re = client.update(up).get();
        //打印返回值
        System.out.println("索引="+re.getIndex());
        System.out.println("类型="+re.getType());
        System.out.println("id="+re.getId());
        System.out.println("版本号="+re.getVersion());
        System.out.println("结果="+re.getResult());
        client.close();
    }

    //更新文档数据upsert  没有创建 有就更新
    @Test
    public void upsert() throws Exception{
        //没有这个文档内容就创建
        IndexRequest index = new IndexRequest("blog", "article", "5");
        IndexRequest re1 = index.source(XContentFactory.jsonBuilder().startObject()
                .field("id", 5)
                .field("titile", "我是最棒的")
                .field("content", "我是一只鱼 ,水里的空气")
                .endObject());
        //有文档内容就更新
        UpdateRequest updateRequest = new UpdateRequest("blog", "article", "5");
        updateRequest.doc(XContentFactory
                .jsonBuilder()
                .startObject()
                .field("id","5")
                .field("title","奋斗是唯一的办法")
                .field("content","加油加油加油加油")
                .endObject());
        updateRequest.upsert(re1);
        //具体更新操作
        UpdateResponse re= client.update(updateRequest).get();
        //打印返回值
        System.out.println("索引="+re.getIndex());
        System.out.println("类型="+re.getType());
        System.out.println("id="+re.getId());
        System.out.println("版本号="+re.getVersion());
        System.out.println("结果="+re.getResult());
        client.close();
    }

    //删除文档
    @Test
    public void delete(){
        client.prepareDelete("blog","article","5").get();
        client.close();
    }

    //查询
    @Test
    public void querymatchall(){
        //查询
        SearchResponse response = client.prepareSearch("blog").setTypes("article").setQuery(QueryBuilders.matchAllQuery()).get();
        //获取查询对象(文档)
        SearchHits hits = response.getHits();
        //打印查询结果条目
        System.out.println("查询结果="+hits.getTotalHits());
        //遍历打印文档内容
        Iterator<SearchHit> iterator = hits.iterator();
        while (iterator.hasNext()){
            SearchHit next = iterator.next();
            System.out.println(next.getSourceAsString());
        }
        //关闭资源
        client.close();
    }

    //分词查询
    @Test
    public void query(){
        //查询
        SearchResponse response = client
                .prepareSearch("blog")
                .setTypes("article")
                .setQuery(QueryBuilders.queryStringQuery("看片"))
                .get();
        //获取查询对象(文档)
        SearchHits hits = response.getHits();
        //打印查询结果条目
        System.out.println("查询结果="+hits.getTotalHits());
        //遍历打印文档内容
        Iterator<SearchHit> iterator = hits.iterator();
        while (iterator.hasNext()){
            SearchHit next = iterator.next();
            System.out.println(next.getSourceAsString());
        }
        //关闭资源
        client.close();
    }

    //词条查询
    @Test
    public void termQuery(){
        //查询
        SearchResponse response = client
                .prepareSearch("blog")
                .setTypes("article")
                .setQuery(QueryBuilders.termQuery("content","看"))
                .get();
        //获取查询对象(文档)
        SearchHits hits = response.getHits();
        //打印查询结果条目
        System.out.println("查询结果="+hits.getTotalHits());
        //遍历打印文档内容
        Iterator<SearchHit> iterator = hits.iterator();
        while (iterator.hasNext()){
            SearchHit next = iterator.next();
            System.out.println(next.getSourceAsString());
        }
        //关闭资源
        client.close();
    }
    //通配符查询  * 表示多个字符(任意字符)   ? 表示单个字符
    @Test
    public void wildcardQuery(){
        //查询
        SearchResponse response = client
                .prepareSearch("blog")
                .setTypes("article")
                .setQuery(QueryBuilders.wildcardQuery("content","*看片*"))
                .get();
        //获取查询对象(文档)
        SearchHits hits = response.getHits();
        //打印查询结果条目
        System.out.println("查询结果="+hits.getTotalHits());
        //遍历打印文档内容
        Iterator<SearchHit> iterator = hits.iterator();
        while (iterator.hasNext()){
            SearchHit next = iterator.next();
            System.out.println(next.getSourceAsString());
        }
        //关闭资源
        client.close();
    }

    //模糊
    @Test
    public void fuzzy(){
        //查询
        SearchResponse response = client
                .prepareSearch("blog")
                .setTypes("article")
                .setQuery(QueryBuilders.fuzzyQuery("title","licene"))
                .get();
        //获取查询对象(文档)
        SearchHits hits = response.getHits();
        //打印查询结果条目
        System.out.println("查询结果="+hits.getTotalHits());
        //遍历打印文档内容
        Iterator<SearchHit> iterator = hits.iterator();
        while (iterator.hasNext()){
            SearchHit next = iterator.next();
            System.out.println(next.getSourceAsString());
        }
        //关闭资源
        client.close();
    }


    //映射相关操作  新创建一个index  没有mapping映射才能运行
    @Test
    public void createMapping() throws Exception {
        // 1设置mapping
        XContentBuilder builder = XContentFactory.jsonBuilder()
                .startObject()
                .startObject("article")
                .startObject("properties")
                .startObject("id1")
                .field("type", "string")
                .field("store", "yes")
                .endObject()
                .startObject("title2")
                .field("type", "string")
                .field("store", "no")
                .endObject()
                .startObject("content")
                .field("type", "string")
                .field("store", "yes")
                .endObject()
                .endObject()
                .endObject()
                .endObject();

        // 2 添加mapping
        PutMappingRequest mapping = Requests.putMappingRequest("blog4").type("article").source(builder);
        client.admin().indices().putMapping(mapping).get();
        // 3 关闭资源
        client.close();
    }
}

 

posted @ 2019-08-25 11:04  lilixia  阅读(2812)  评论(0编辑  收藏  举报