转载

使用Jest查询Elasticsearch

近期需要在项目中将Elasticsearch查询由Python切换到Java才可以在公司的项目中正常使用,而且项目使用的还是Java7的版本,而默认的Elasticsearch需要Java8的支持,只好降级处理了。

这里我们的demo,使用的Elasticsearch版本是 6.3.1 ,对应的Java版本为8,我们使用Jest库来简化操作。

首先使用maven下载对应的依赖库:

<?xml version="1.0"?>  
<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.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  
    <modelVersion>4.0.0</modelVersion>  
    <groupId>com.es</groupId>  
    <artifactId>es</artifactId>  
    <version>1.0</version>   
    <dependencies>  
        <dependency>  
            <groupId>io.searchbox</groupId>  
            <artifactId>jest</artifactId>  
            <version>6.3.1</version>  
        </dependency>  
    </dependencies>  
</project>

在这个过程中,我们需要配置对应maven源为国内的阿里云,不然其下载速度不堪入目。

我们修改maven配置文件 settings.xml 中mirrors中的节点,添加如下代码:

<mirror>    
    <id>nexus-aliyun</id>    
    <mirrorOf>central</mirrorOf>      
    <name>Nexus aliyun</name>    
    <url>http://maven.aliyun.com/nexus/content/groups/public</url>    
</mirror>

接着我们下载对应的依赖包:

mvn dependency:copy-dependencies -DoutputDirectory=libs

在这里,我们设置其下载目录为当前目录下libs目录,接着maven就会帮我们自动下载对应的包了。

下面我们开始编写我们的程序,1个非常简单的程序:

import java.io.IOException;  
import java.util.*;  
import java.util.Objects;  
import com.google.gson.GsonBuilder;  
import io.searchbox.client.*;  
import io.searchbox.core.*;  
import io.searchbox.client.config.*;  

public class ESClient {  
    private static final String ES_HOST = "http://127.0.0.1";  
    private static final int ES_HTTP_PORT = 9200;  
    private static JestClient client;  

    public static synchronized JestClient getClient(){  
        if(client==null){  
            build();  
        }  
        return client;  
    }  

    public static void close(JestClient client){  
        if(!Objects.isNull(client)){  
            try{  
                client.close();  
            }catch (Exception e){  
                e.printStackTrace();  
            }  
        }  
    }  

    private static void build() {  
        JestClientFactory factory = new JestClientFactory();  
        //实例化客户端工厂类  
        factory.setHttpClientConfig(new HttpClientConfig.Builder(ES_HOST+":"+ES_HTTP_PORT)  
                                    .multiThreaded(true)  
                                    .defaultMaxTotalConnectionPerRoute(2)  
                                    .maxTotalConnection(2) //设置总连接数为2个  
                                    .connTimeout(10000) //设置连接超时时间  
                                    .readTimeout(10000)    //设置读取超时时间  
                                    .gson(new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create()) //设置JSON日期格式  
                                    .build());  
        client = factory.getObject();  
    }  

    public static void main(String[] args) throws IOException {  
        JestClient client = getClient();  
        String query = "{/"query/":{/"match_all/":{}}}";  
        Search.Builder searchBuilder = new Search.Builder(query).addIndex("demo").addType("person");  
        SearchResult result = client.execute(searchBuilder.build());  
        System.out.println(result.toString());  
    }  
}

在这里,导入对应的包,主要是下面这3行代码:

import io.searchbox.client.*;  
import io.searchbox.core.*;  
import io.searchbox.client.config.*;

在方法build中,我们实例化1个 JestClientFactory 类,之后进行对应的配置,最后通过其工厂类的 getObject 得到对应的客户端对象。

而在main入口中,我们通过 getClient 方法得到对应的实例后,之后构建1个JSON字符串,之后调用 Search.Builder 对JSON字符串进行构建,并添加对应的Index和DocType后,我们通过客户端实例的execute方法来执行,最后通过其查询的结果转换为字符串即可。

其结果如下:

dog@debian:~/es$ javac -classpath ".:libs/*" ESClient.java  
dog@debian:~/es$ java -classpath ".:libs/*" ESClient  
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".  
SLF4J: Defaulting to no-operation (NOP) logger implementation  
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.  
Result: {"took":7,"timed_out":false,"_shards":{"total":5,"successful":5,"skipped":0,"failed":0},"hits":{"total":5,"max_score":1.0,"hits":[{"_index":"demo","_type":"person","_id":"1g3l82UB8TY7aIKswO1s","_score":1.0,"_source":{"username":"王五","gender":"男","age":"21","region":"杭州","tags":["吃货","技术大牛"]}},{"_index":"demo","_type":"person","_id":"1A3l82UB8TY7aIKsvu2-","_score":1.0,"_source":{"username":"张三","gender":"男","age":"20","region":"中山","tags":["吃货","宅男"]}},{"_index":"demo","_type":"person","_id":"1Q3l82UB8TY7aIKswO0f","_score":1.0,"_source":{"username":"李四","gender":"男","age":"25","region":"金华","tags":["宅男","技术大牛"]}},{"_index":"demo","_type":"person","_id":"2A3l82UB8TY7aIKswe0G","_score":1.0,"_source":{"username":"熊莎莎","gender":"女","age":"25","region":"河源","tags":["吃货","中二"]}},{"_index":"demo","_type":"person","_id":"1w3l82UB8TY7aIKswO2-","_score":1.0,"_source":{"username":"莫晓佳","gender":"女","age":"23","region":"苏州","tags":["麦霸","吃货"]}}]}}, isSucceeded: true, response code: 200, error message: null

这个过程不得不说还是有点问题的,由于项目比较赶,于是趁早起的时候编写了上述代码,走了不少弯路,还是有不足了。只能等上班再进行完善了。

原文  http://blog.52sox.com/use-jest-for-elasticsearch/
正文到此结束
Loading...