使用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
這個過程不得不說還是有點問題的,由於專案比較趕,於是趁早起的時候編寫了上述程式碼,走了不少彎路,還是有不足了。只能等上班再進行完善了。