使用Java API访问集群

<dependencies>
    <dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>transport</artifactId>
        <version>6.7.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.9.1</version>
    </dependency>


    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>6.14.3</version>
        <scope>test</scope>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.47</version>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
    </plugins>
</build>

代码示例:增删改查

package elasticsearch;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.Requests;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.Test;

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

import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;


public class ElasticsearchDemo {




    public TransportClient getClient() throws UnknownHostException {

        Settings settings = Settings.builder().put("cluster.name", "myes").build();


        TransportAddress transportAddress1 = new TransportAddress(InetAddress.getByName("192.168.154.100"), 9300);
        TransportAddress transportAddress2 = new TransportAddress(InetAddress.getByName("192.168.154.110"), 9300);
        TransportAddress transportAddress3 = new TransportAddress(InetAddress.getByName("192.168.154.120"), 9300);

        TransportClient    client = new PreBuiltTransportClient(settings)
                .addTransportAddress(transportAddress1)
                .addTransportAddress(transportAddress2)
                .addTransportAddress(transportAddress3);
        System.out.println(client.toString());

        return client;
    }


    @Test
    public void createIndex() throws UnknownHostException {
        TransportClient client = getClient();
        String json = "{" +
                "\"user\":\"kimchy\"," +
                "\"postDate\":\"2013-01-30\"," +
                "\"message\":\"travelying out Elasticsearch\"" +
                "}";


        IndexRequestBuilder indexRequestBuilder = client.prepareIndex("myindex1", "article", "1").setSource(json, XContentType.JSON);

        // 调用触发真正的请求
        indexRequestBuilder.get();

        closeClient(client);
    }


    @Test
    public void createMapIndex() throws UnknownHostException {
        TransportClient client = getClient();
        HashMap<String, String> map = new HashMap<>();
        map.put("name", "小哥");
        map.put("age", "12");
        map.put("sex", "男");
        map.put("address", "小区");
        IndexRequestBuilder indexRequestBuilder = client.prepareIndex("myindex1", "article", "2").setSource(map);

        // 调用触发真正的请求
        indexRequestBuilder.get();

        closeClient(client);
    }

    @Test
    public void create3Index() throws IOException {
        TransportClient client = getClient();
        HashMap<String, String> map = new HashMap<>();

        map.put("name", "小王");
        map.put("age", "12");
        map.put("sex", "男");
        map.put("address", "胜古");
        IndexRequestBuilder indexRequestBuilder = client
                .prepareIndex("myindex1", "article", "3")
                .setSource(
                        new XContentFactory().jsonBuilder().startObject()
                                .field("name","李四")
                .field("age","55")
                .field(" address","河南省").endObject());

        // 调用触发真正的请求
        IndexResponse indexResponse = indexRequestBuilder.get();

        closeClient(client);
    }

    @Test
    public void create4Index() throws IOException {
        TransportClient client = getClient();
        Person person = new Person();
        person.setAge(12);
        person.setAddress("河北");
        person.setId(1);
        person.setName("小王");
        person.setPhone("17890908989");
        person.setSay("hello");
        person.setSex(1);

        String jsonString = JSON.toJSONString(person);


        IndexRequestBuilder indexRequestBuilder = client
                .prepareIndex("myindex1", "article", "4")
                .setSource(
                        jsonString,XContentType.JSON);

        // 调用触发真正的请求
        IndexResponse indexResponse = indexRequestBuilder.get();
        RestStatus status = indexResponse.status();
        System.out.println("status:"+ status);

        closeClient(client);
    }

    @Test
    public void addBatch() throws IOException {
        TransportClient client = getClient();

        BulkRequestBuilder bulkRequestBuilder = client.prepareBulk();

        Person person1 = new Person();
        person1.setAge(12);
        person1.setAddress("河北");
        person1.setId(1);
        person1.setName("吴邪");
        person1.setPhone("17890908989");
        person1.setSay("hello");
        person1.setSex(1);
        Person person2 = new Person();
        person2.setAge(12);
        person2.setAddress("河北");
        person2.setId(1);
        person2.setName("胖子");
        person2.setPhone("17890908989");
        person2.setSay("hello");
        person2.setSex(1);
        Person person3 = new Person();
        person3.setAge(12);
        person3.setAddress("河北");
        person3.setId(1);
        person3.setName("小哥");
        person3.setPhone("17890908989");
        person3.setSay("hello");
        person3.setSex(1);

        String jsonString1 = JSON.toJSONString(person1);
        String jsonString2 = JSON.toJSONString(person2);
        String jsonString3 = JSON.toJSONString(person3);




        IndexRequestBuilder indexRequestBuilder1 = client
                .prepareIndex("myindex1", "article", "5")
                .setSource(
                        jsonString1,XContentType.JSON);
        IndexRequestBuilder indexRequestBuilder2 = client
                .prepareIndex("myindex1", "article", "6")
                .setSource(
                        jsonString2,XContentType.JSON);
        IndexRequestBuilder indexRequestBuilder3 = client
                .prepareIndex("myindex1", "article", "7")
                .setSource(
                        jsonString3,XContentType.JSON);


        BulkRequestBuilder builder = bulkRequestBuilder.add(indexRequestBuilder1)
                .add(indexRequestBuilder2)
                .add(indexRequestBuilder3);


        BulkResponse bulkItemResponses = builder.get();

        closeClient(client);
    }


    @Test
    public void updateIndex() throws IOException {
        TransportClient client = getClient();
        HashMap<String, String> map = new HashMap<>();
        map.put("phone", "15688888888");

         client.prepareUpdate("myindex1", "article", "5").setDoc(map).get();

        closeClient(client);
    }


    /**
     *
     * 删除索引
     **/
    @Test
    public void deleteIndex() throws IOException {
        TransportClient client = getClient();

        client.prepareDelete("myindex1", "article", "1").get();

        closeClient(client);
    }


    /**
     *
     * 删除索引库
     **/
    @Test
    public void deleteIndexDB() throws IOException {
        TransportClient client = getClient();

        client.admin().indices().prepareDelete("myindex1").execute().actionGet();

        closeClient(client);
    }





    /**
     * 初始化一批数据到索引库当中去准备做查询使用
     * 注意这里初始化的时候,需要给我们的数据设置分词属性
     * @throws Exception
     */
    @Test
    public void createIndexBatch() throws Exception {
//        Settings settings = Settings
//                .builder()
//                .put("cluster.name", "myes") //节点名称, 在es配置的时候设置
//                //自动发现我们其他的es的服务器
//                .put("client.transport.sniff", "true")
//                .build();
//        //创建客户端
//        TransportClient client = new PreBuiltTransportClient(settings)
//                .addTransportAddress(new TransportAddress(InetAddress.getByName("node01"), 9300));//以本机作为节点
        TransportClient client = getClient();

        //创建映射
        XContentBuilder mapping = jsonBuilder()
                .startObject()
                .startObject("properties")
                //      .startObject("m_id").field("type","keyword").endObject()
                .startObject("id").field("type", "integer").endObject()
                .startObject("name").field("type", "text").field("analyzer", "ik_max_word").endObject()
                .startObject("age").field("type", "integer").endObject()
                .startObject("sex").field("type", "text").field("analyzer", "ik_max_word").endObject()
                .startObject("address").field("type", "text").field("analyzer", "ik_max_word").endObject()
                .startObject("phone").field("type", "text").endObject()
                .startObject("email").field("type", "text").endObject()
                .startObject("say").field("type", "text").field("analyzer", "ik_max_word").endObject()
                .endObject()
                .endObject();
        //pois:索引名   cxyword:类型名(可以自己定义)
        PutMappingRequest putmap = Requests.putMappingRequest("indexsearch").type("mysearch").source(mapping);
        //创建索引
        client.admin().indices().prepareCreate("indexsearch").execute().actionGet();
        //为索引添加映射
        client.admin().indices().putMapping(putmap).actionGet();


        BulkRequestBuilder bulkRequestBuilder = client.prepareBulk();
        Person lujunyi = new Person(2, "玉麒麟卢俊义", 28, 1, "水泊梁山", "17666666666", "lujunyi@itcast.com","hello world今天天气还不错");
        Person wuyong = new Person(3, "智多星吴用", 45, 1, "水泊梁山", "17666666666", "wuyong@itcast.com","行走四方,抱打不平");
        Person gongsunsheng = new Person(4, "入云龙公孙胜", 30, 1, "水泊梁山", "17666666666", "gongsunsheng@itcast.com","走一个");
        Person guansheng = new Person(5, "大刀关胜", 42, 1, "水泊梁山", "17666666666", "wusong@itcast.com","我的大刀已经饥渴难耐");
        Person linchong = new Person(6, "豹子头林冲", 18, 1, "水泊梁山", "17666666666", "linchong@itcast.com","梁山好汉");
        Person qinming = new Person(7, "霹雳火秦明", 28, 1, "水泊梁山", "17666666666", "qinming@itcast.com","不太了解");
        Person huyanzhuo = new Person(8, "双鞭呼延灼", 25, 1, "水泊梁山", "17666666666", "huyanzhuo@itcast.com","不是很熟悉");
        Person huarong = new Person(9, "小李广花荣", 50, 1, "水泊梁山", "17666666666", "huarong@itcast.com","打酱油的");
        Person chaijin = new Person(10, "小旋风柴进", 32, 1, "水泊梁山", "17666666666", "chaijin@itcast.com","吓唬人的");
        Person zhisheng = new Person(13, "花和尚鲁智深", 15, 1, "水泊梁山", "17666666666", "luzhisheng@itcast.com","倒拔杨垂柳");
        Person wusong = new Person(14, "行者武松", 28, 1, "水泊梁山", "17666666666", "wusong@itcast.com","二营长。。。。。。");

        bulkRequestBuilder.add(client.prepareIndex("indexsearch", "mysearch", "1")
                .setSource(JSONObject.toJSONString(lujunyi), XContentType.JSON)
        );
        bulkRequestBuilder.add(client.prepareIndex("indexsearch", "mysearch", "2")
                .setSource(JSONObject.toJSONString(wuyong), XContentType.JSON)
        );
        bulkRequestBuilder.add(client.prepareIndex("indexsearch", "mysearch", "3")
                .setSource(JSONObject.toJSONString(gongsunsheng), XContentType.JSON)
        );
        bulkRequestBuilder.add(client.prepareIndex("indexsearch", "mysearch", "4")
                .setSource(JSONObject.toJSONString(guansheng), XContentType.JSON)
        );
        bulkRequestBuilder.add(client.prepareIndex("indexsearch", "mysearch", "5")
                .setSource(JSONObject.toJSONString(linchong), XContentType.JSON)
        );
        bulkRequestBuilder.add(client.prepareIndex("indexsearch", "mysearch", "6")
                .setSource(JSONObject.toJSONString(qinming), XContentType.JSON)
        );
        bulkRequestBuilder.add(client.prepareIndex("indexsearch", "mysearch", "7")
                .setSource(JSONObject.toJSONString(huyanzhuo), XContentType.JSON)
        );
        bulkRequestBuilder.add(client.prepareIndex("indexsearch", "mysearch", "8")
                .setSource(JSONObject.toJSONString(huarong), XContentType.JSON)
        );
        bulkRequestBuilder.add(client.prepareIndex("indexsearch", "mysearch", "9")
                .setSource(JSONObject.toJSONString(chaijin), XContentType.JSON)
        );
        bulkRequestBuilder.add(client.prepareIndex("indexsearch", "mysearch", "10")
                .setSource(JSONObject.toJSONString(zhisheng), XContentType.JSON)
        );
        bulkRequestBuilder.add(client.prepareIndex("indexsearch", "mysearch", "11")
                .setSource(JSONObject.toJSONString(wusong), XContentType.JSON)
        );

        bulkRequestBuilder.get();
        closeClient(client);

    }













    public void closeClient(TransportClient client ){
        client.close();
    }


}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值