Elasticseach java api使用TransportClient

Elasticseach java api 查询

如果是springboot的话,查询等方式直接推荐使用Jpa,通过这种凡是来操作Elasticsearch的数据,只要根据jpa的方法命名规则来命名方法即可,参考官方文档 
但是需要注意springboot与Elasticsearch版本的对应关系官方git-wiki说得很清楚里面还有一个矩阵图,所以大家还是需要注意一下的.

  • springbootSpring Data ElasticsearchElasticsearch Version三者之间的版本对应关系如下:
springboot version(x) Spring Data Elasticsearch version(y) Elasticsearch Version(z)
x <= 1.3.5 y <= 1.3.4 z <= 1.7.2*
x >= 1.4.x 2.0.0 <=y < 5.0.0** 2.0.0 <= z < 5.0.0**

经过博主的实践,其中springboot版本为2.0.0是支持Elasticsearch5.5+的,但是不支持Elasticsearch6.0+.这条请做参考,以实际情况为准.

本次博文使用的是Elasticsearch5.5.1,官方下载地址.

添加Maven的依赖

        
            org.elasticsearch.client
            transport
            5.5.3
        
        
        
            org.apache.logging.log4j
            log4j-core
            2.8.2
        
  • 注意点,还需要添加一个插件,这是很多人都会忽略的,如果只有上面的依赖是不能够满足需求的.
            
                org.apache.maven.plugins
                maven-shade-plugin
                2.4.1
                
                    
                        package
                        shade
                        
                            
                                
                                    
                                    com.ydw.esdemo.EsdemoApplication
                                
                            
                        
                    
                
            

创建Client客户端

    @Bean
    public TransportClient transportClient(){
        try {
            TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));
            return client;
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return null;
    }

测试例子

package com.ydw.esdemo;

import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.index.reindex.DeleteByQueryAction;
import org.elasticsearch.rest.RestStatus;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.IOException;
import java.util.Date;
import java.util.concurrent.ExecutionException;

import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.index.query.QueryBuilders.matchQuery;

@RunWith(SpringRunner.class)
@SpringBootTest
public class EsdemoApplicationTests {

    @Autowired
    TransportClient transportClient;

    @Test
    //创建索引
    public void contextLoads() throws IOException {
        IndexResponse response = transportClient.prepareIndex("twitter", "tweet", "1")
                .setSource(jsonBuilder()
                        .startObject()
                        .field("user", "kimchy")
                        .field("postDate", new Date())
                        .field("message", "trying out Elasticsearch")
                        .endObject()
                )
                .get();
    }


    @Test
    //添加文档
    public void addDocuments(){
        String json = "{" +
                "\"user\":\"kimchy\"," +
                "\"postDate\":\"2013-01-30\"," +
                "\"message\":\"trying out Elasticsearch\"" +
                "}";

        IndexResponse response = transportClient.prepareIndex("twitter", "tweet")
                .setSource(json, XContentType.JSON)
                .get();
        // 索引名字
        String _index = response.getIndex();
        // 类型
        String _type = response.getType();
        // 文档ID
        String _id = response.getId();
        // 文档版本号
        long _version = response.getVersion();
        RestStatus status = response.status();
        System.out.println(_index+"_"+_type+"_"+_id);
    }


    @Test
    //根据id查找文档
    public void findById(){
        GetResponse response = transportClient.prepareGet("twitter", "tweet", "1").get();
        System.out.println(response.getSource());
    }

    @Test
    //根据id删除
    public void deletById(){
        DeleteResponse response = transportClient.prepareDelete("twitter", "tweet", "1").get();
    }

    //根据查询条件来进行删除
    @Test
    public void deleteByQuery(){
        BulkByScrollResponse response =
                DeleteByQueryAction.INSTANCE.newRequestBuilder(transportClient)
                        //先查找出名字为kimchy的的用户,然后在删除
                        .filter(matchQuery("user", "kimchy"))
                        //这边设置索引的名字
                        .source("twitter")
                        .get();
        //获得被删除的数量
        long deleted = response.getDeleted();
        System.out.println(deleted);
    }

    //更新文档
    public void update() throws IOException, ExecutionException, InterruptedException {
        UpdateRequest updateRequest = new UpdateRequest();
        updateRequest.index("twitter");
        updateRequest.type("tweet");
        updateRequest.id("1");
        updateRequest.doc(jsonBuilder()
                .startObject()
                .field("user", "changeName")
                .endObject());
        transportClient.update(updateRequest).get();
    }

    //批量操作
    public void bulkProcessor()throws Exception{
        BulkRequestBuilder bulkRequest = transportClient.prepareBulk();

// either use client#prepare, or use Requests# to directly build index/delete requests
        bulkRequest.add(transportClient.prepareIndex("twitter", "tweet", "1")
                .setSource(jsonBuilder()
                        .startObject()
                        .field("user", "kimchy")
                        .field("postDate", new Date())
                        .field("message", "trying out Elasticsearch")
                        .endObject()
                )
        );

        bulkRequest.add(transportClient.prepareIndex("twitter", "tweet", "2")
                .setSource(jsonBuilder()
                        .startObject()
                        .field("user", "kimchy")
                        .field("postDate", new Date())
                        .field("message", "another post")
                        .endObject()
                )
        );

        BulkResponse bulkResponse = bulkRequest.get();
        if (bulkResponse.hasFailures()) {
            // 遍历bulkResponse中的每个对象,这些都是操作失败的后续处理
        }
    }

    //===============================搜索的api=================================

    public void multiIndexTermQueryAndFilterBySize(){
        SearchResponse response = transportClient.prepareSearch("index1", "index2")//这边可以填写多个索引的名字
                .setTypes("type1", "type2")//这边可以填写多个type
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                .setQuery(QueryBuilders.termQuery("fildName", "test"))    //设置termQuery
                .setPostFilter(QueryBuilders.rangeQuery("age").from(12).to(18))     // 添加过滤器
                .setFrom(0).setSize(60).setExplain(true)//设置数量
                .get();
        //解析response
    }
    //自动匹配,会分词
    public void mymatchQuery(){
        QueryBuilder qb = QueryBuilders.matchQuery(
                "name",//字段
                "kimchy elasticsearch"//搜索的文本
        );
        SearchResponse response = transportClient.prepareSearch("index").setQuery(qb).get();
        //解析response
    }

}

 

你可能感兴趣的:(大数据)