Browse Source

使用JEST实现ElasticSearch访问

huangxy 6 years ago
parent
commit
c51b35fc27

+ 6 - 0
study/pom.xml

@@ -27,6 +27,12 @@
     <dependencies>
         <!--搜索引擎-->
         <dependency>
+            <groupId>org.elasticsearch</groupId>
+            <artifactId>elasticsearch</artifactId>
+            <version>5.5.1</version>
+        </dependency>
+
+        <dependency>
             <groupId>io.searchbox</groupId>
             <artifactId>jest</artifactId>
             <version>5.3.3</version>

+ 24 - 0
study/src/main/java/com/hxy/study/config/MainConfig.java

@@ -1,14 +1,38 @@
 package com.hxy.study.config;
 
 import com.hxy.study.util.HttpClientHelper;
+import io.searchbox.client.JestClient;
+import io.searchbox.client.JestClientFactory;
+import io.searchbox.client.config.HttpClientConfig;
+import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.Configuration;
 
+import java.net.UnknownHostException;
+
 @Configuration
 public class MainConfig {
+    @Autowired
+    private ElasticSearchConfig elasticSearchConfig;
+
     @Bean("httpClientHelper")
     public HttpClientHelper httpClientHelper() {
         return new HttpClientHelper();
     }
 
+    @Bean
+    public JestClient client() throws UnknownHostException {
+        // Construct a new Jest client according to configuration via factory
+        JestClientFactory factory = new JestClientFactory();
+        factory.setHttpClientConfig(new HttpClientConfig
+                .Builder("http://" + elasticSearchConfig.getServerIp() + ":" + elasticSearchConfig.getServerPort())
+                .multiThreaded(true)
+                //Per default this implementation will create no more than 2 concurrent connections per given route
+                .defaultMaxTotalConnectionPerRoute(2)
+                // and no more 20 connections in total
+                .maxTotalConnection(20)
+                .build());
+        JestClient client = factory.getObject();
+        return client;
+    }
 }

+ 44 - 0
study/src/main/java/com/hxy/study/controller/dto/Paper.java

@@ -0,0 +1,44 @@
+package com.hxy.study.controller.dto;
+
+public class Paper {
+
+    private Long id;
+
+    private String name;
+
+    private String author;
+
+    private String type;
+
+    public Long getId() {
+        return id;
+    }
+
+    public void setId(Long id) {
+        this.id = id;
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public String getAuthor() {
+        return author;
+    }
+
+    public void setAuthor(String author) {
+        this.author = author;
+    }
+
+    public String getType() {
+        return type;
+    }
+
+    public void setType(String type) {
+        this.type = type;
+    }
+}

+ 1 - 1
study/src/main/resources/application.yaml

@@ -1,3 +1,3 @@
 elastic-search:
   serverIp: 192.168.232.157
-  serverPort: 9300
+  serverPort: 9200

+ 40 - 32
study/src/test/java/com/hxy/study/SearchClientTest.java

@@ -1,16 +1,13 @@
 package com.hxy.study;
 
 import com.hxy.study.config.ElasticSearchConfig;
-import com.hxy.study.controller.dto.Account;
-import com.hxy.study.util.HttpCallback;
 import com.hxy.study.util.HttpClientHelper;
 import io.searchbox.client.JestClient;
-import io.searchbox.client.JestClientFactory;
-import io.searchbox.client.JestResult;
-import io.searchbox.client.config.HttpClientConfig;
-import io.searchbox.core.Get;
-import org.apache.commons.httpclient.Cookie;
-import org.apache.commons.httpclient.HttpMethod;
+import io.searchbox.core.Search;
+import io.searchbox.core.SearchResult;
+import org.elasticsearch.index.query.QueryBuilder;
+import org.elasticsearch.index.query.QueryBuilders;
+import org.elasticsearch.search.builder.SearchSourceBuilder;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.springframework.beans.factory.annotation.Autowired;
@@ -21,7 +18,6 @@ import java.io.IOException;
 import java.net.InetAddress;
 import java.net.UnknownHostException;
 import java.util.HashMap;
-import java.util.List;
 import java.util.Map;
 
 @RunWith(SpringRunner.class)
@@ -34,6 +30,9 @@ public class SearchClientTest {
     @Autowired
     private HttpClientHelper httpClientHelper;
 
+    @Autowired
+    private JestClient jestClient;
+
     @Test
     public void getInterAddress() {
         try {
@@ -45,28 +44,40 @@ public class SearchClientTest {
     }
 
 
+    /**
+     * 使用Jest 利用 Http res接口访问 ElasticSearch
+     * 查询条件用的是ElasticSearch官方提供的类
+     */
     @Test
-    public void test() {
-        // Construct a new Jest client according to configuration via factory
-        JestClientFactory factory = new JestClientFactory();
-        factory.setHttpClientConfig(new HttpClientConfig
-                .Builder("http://192.168.232.157:9200")
-                .multiThreaded(true)
-                //Per default this implementation will create no more than 2 concurrent connections per given route
-                .defaultMaxTotalConnectionPerRoute(2)
-                // and no more 20 connections in total
-                .maxTotalConnection(20)
-                .build());
-        JestClient client = factory.getObject();
-
-        Get get = new Get.Builder("accounts", "1").build();
+    public void testJestEs() {
+        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
+        QueryBuilder queryBuilder = QueryBuilders
+                .matchQuery("name", "英语试题");//单值完全匹配查询
+        QueryBuilder queryBuilderAuthor = QueryBuilders.matchQuery("author", "马");
+        QueryBuilder allClause = QueryBuilders.boolQuery().should(queryBuilder).should(queryBuilderAuthor);
+        searchSourceBuilder.query(allClause);
+        searchSourceBuilder.size(10);
+        searchSourceBuilder.from(0);
+
+        String query = searchSourceBuilder.toString();
+        System.out.println(query);
+        Search search = new Search.Builder(query)
+                .addIndex("t_paper")
+                .build();
         try {
-            JestResult result = client.execute(get);
-            List<Account> account = result.getSourceAsObjectList(Account.class);
-            System.out.println(account);
+            SearchResult result = jestClient.execute(search);
+            System.out.println(result.getJsonString());
         } catch (IOException e) {
             e.printStackTrace();
         }
+
+        // other examples
+//        QueryBuilder levelClause = QueryBuilders.termsQuery("loglevel.keyword", "ERROR", "FATAL");
+//        QueryBuilder timeClause = QueryBuilders.rangeQuery("logtime.keyword").from(startTime).to(endTime);
+//        QueryBuilder queryBuilder = QueryBuilders.matchQuery("logclass.keyword", "com.huohuo.Test");
+        // and/or/not等:涉及到多条件查询用boolQuery,组合多个query。must表示and,mustNot表示not,should表示or。
+
+
     }
 
 
@@ -80,12 +91,9 @@ public class SearchClientTest {
 
         data.put("query", match);
         try {
-            httpClientHelper.get(url, null, new HttpCallback() {
-                @Override
-                public void callback(int httpstatus, HttpMethod httpMethod, Cookie[] cookies) throws IOException {
-                    System.out.println(httpstatus);
-                    System.out.println(httpMethod.getResponseBodyAsString());
-                }
+            httpClientHelper.get(url, null, (httpstatus, httpMethod, cookies) -> {
+                System.out.println(httpstatus);
+                System.out.println(httpMethod.getResponseBodyAsString());
             });
         } catch (IOException e) {
             e.printStackTrace();