ElasticSearch5.X—模糊查询和获取所有索引字段

2018/04/23 13:45
阅读数 171

最近在做一个分布式数据存储的项目,需要用到ElastciSearch加速数据查询,其中部分功能需要进行模糊查询和统计索引库中已经建立的索引字段,网上查阅了很多资料,最终把这两个问题解决了,不容易!下面的代码是具体的功能实现。

[java] view plain copy
 
  1. import java.net.InetAddress;  
  2. import java.net.UnknownHostException;  
  3. import java.util.ArrayList;  
  4. import java.util.HashMap;  
  5. import java.util.List;  
  6. import java.util.Map;  
  7. import java.util.Set;  
  8. import java.io.IOException;  
  9. import org.elasticsearch.action.admin.indices.create.CreateIndexRequestBuilder;  
  10. import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;  
  11. import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsRequest;  
  12. import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;  
  13. import org.elasticsearch.action.admin.indices.exists.types.TypesExistsResponse;  
  14. import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;  
  15. import org.elasticsearch.action.admin.indices.stats.IndexStats;  
  16. import org.elasticsearch.action.admin.indices.stats.IndicesStatsResponse;  
  17. import org.elasticsearch.action.delete.DeleteResponse;  
  18. import org.elasticsearch.action.get.GetResponse;  
  19. import org.elasticsearch.action.index.IndexResponse;  
  20. import org.elasticsearch.action.search.SearchResponse;  
  21. import org.elasticsearch.client.Client;  
  22. import org.elasticsearch.client.IndicesAdminClient;  
  23. import org.elasticsearch.client.Requests;  
  24. import org.elasticsearch.cluster.ClusterState;  
  25. import org.elasticsearch.cluster.metadata.IndexMetaData;  
  26. import org.elasticsearch.cluster.metadata.MappingMetaData;  
  27. import org.elasticsearch.common.settings.Settings;  
  28. import org.elasticsearch.common.transport.InetSocketTransportAddress;  
  29. import org.elasticsearch.common.xcontent.XContentBuilder;  
  30. import org.elasticsearch.common.xcontent.XContentFactory;  
  31. import org.elasticsearch.index.query.BoolQueryBuilder;  
  32. import org.elasticsearch.index.query.QueryBuilder;  
  33. import org.elasticsearch.index.query.QueryBuilders;  
  34. import org.elasticsearch.search.SearchHit;  
  35. import org.elasticsearch.search.SearchHitField;  
  36. import org.elasticsearch.search.SearchHits;  
  37. import org.elasticsearch.transport.client.PreBuiltTransportClient;  
  38.   
  39. public class EsIndexwildcardQueryAndFieldStatistic {  
  40.     private static Client client;  
  41.     private static Settings settings;  
  42.     private static String index = "blog21";  
  43.     private static String type = "article21";  
  44.   
  45.     // 注意区分5.X系列的ES版本client初始化  
  46.     static {  
  47.         settings = Settings.builder()  
  48.                 .put("cluster.name", "backup_elasticsearch")  
  49.                 .put("client.transport.sniff", true).build();  
  50.         try {  
  51.             client = new PreBuiltTransportClient(settings)  
  52.                     .addTransportAddress(new InetSocketTransportAddress(  
  53.                             InetAddress.getByName("172.17.173.21"), 9300));  
  54.         } catch (UnknownHostException e) {  
  55.   
  56.             e.printStackTrace();  
  57.         }  
  58.     }  
  59.   
  60.     public static void main(String[] args) throws IOException {  
  61.         // 创建索引  
  62.         CreateIndexResponse indexResponse = client.admin().indices()  
  63.                 .prepareCreate(index).get();  
  64.         // 建立映射  
  65.         XContentBuilder mapping = XContentFactory.jsonBuilder().startObject()  
  66.                 .startObject("properties").startObject("PolicyCode")  
  67.                 .field("type", "keyword").field("store", "yes").endObject()  
  68.                 .startObject("ServiceId").field("type", "keyword")  
  69.                 .field("store", "yes").endObject().startObject("CreateTime")  
  70.                 .field("type", "date").field("format", "yyyy-MM-dd HH:mm:ss")  
  71.                 .field("store", "yes").endObject().endObject().endObject();  
  72.         PutMappingRequest mappingRequest = Requests.putMappingRequest(index)  
  73.                 .source(mapping).type(type);  
  74.         client.admin().indices().putMapping(mappingRequest).actionGet();  
  75.   
  76.         // 插入数据  
  77.         for (int i = 0; i < 10; i++) {  
  78.             HashMap<String, Object> hashMap = new HashMap<String, Object>();  
  79.             if (i % 2 == 0) {  
  80.                 hashMap.put("PolicyCode", "5674504720");  
  81.                 hashMap.put("ServiceId", "SE2");  
  82.                 hashMap.put("CreateTime", "2016-08-21 00:00:01");  
  83.             } else {  
  84.                 hashMap.put("PolicyCode", "666666666");  
  85.                 hashMap.put("ServiceId", "SE3");  
  86.                 hashMap.put("CreateTime", "2016-10-21 00:00:01");  
  87.             }  
  88.             client.prepareIndex(index, type).setSource(hashMap).get();  
  89.         }  
  90.         // 精确查询  
  91.         QueryBuilder qb1 = QueryBuilders.termQuery("PolicyCode", "5674504720");  
  92.         // 模糊查询, “*”表示0到多个字符,而使用“?”表示一个字符  
  93.         QueryBuilder qb2 = QueryBuilders.wildcardQuery("ServiceId", "*SE*");  
  94.         QueryBuilder qb3 = QueryBuilders.wildcardQuery("ServiceId", "SE?");  
  95.         QueryBuilder qb4 = QueryBuilders.wildcardQuery("ServiceId", "?SE?");  
  96.         QueryBuilder qb5 = QueryBuilders.wildcardQuery("ServiceId", "SE2?");  
  97.         QueryBuilder qb6 = QueryBuilders.wildcardQuery("ServiceId", "SE2*");  
  98.         QueryBuilder qb7 = QueryBuilders.wildcardQuery("ServiceId", "*SE3*");  
  99.   
  100. //       SearchResponse response = client.prepareSearch(index)  
  101. //       .setTypes(type)  
  102. //       .setQuery(qb3)  
  103. //       .execute()  
  104. //       .actionGet();  
  105.                  
  106.              try {  
  107.             Thread.sleep(2000);     //ES在新建 索引库后并往里面插入数据时是异步的,需要等待一定时间,才能查询到索引库中的数据  
  108.         } catch (InterruptedException e) {  
  109.             e.printStackTrace();  
  110.         }  
  111.         SearchResponse response = client.prepareSearch(index).setTypes(type)  
  112.                 .setQuery(QueryBuilders.boolQuery().must(qb2)).get();  
  113.   
  114.         SearchHits hits = response.getHits();  
  115.         if (hits.totalHits > 0) {  
  116.             for (SearchHit hit : hits) {  
  117.                 System.out.println("score:" + hit.getScore() + ":\t"  
  118.                         + hit.getId());  
  119.             }  
  120.         } else {  
  121.             System.out.println("搜到0条结果");  
  122.         }  
[java] view plain copy
 
  1.               //获取索引库字段  
  2.         List<String> fieldList = new ArrayList<String>();  
  3.         ClusterState cs = client.admin().cluster().prepareState()  
  4.                 .setIndices(index).execute().actionGet().getState();  
  5.         IndexMetaData imd = cs.getMetaData().index(index);  
  6.         MappingMetaData mdd = imd.mapping(type);  
  7.         Map<String, Object> mapProperties = new HashMap<String, Object>();  
  8.   
  9.         try {  
  10.             mapProperties = mdd.getSourceAsMap();  
  11.         } catch (IOException e) {  
  12.             e.printStackTrace();  
  13.         }  
  14.         fieldList = getIndexFieldList("", mapProperties);  
  15.   
  16.         System.out.println("Field List:");  
  17.         for (String field : fieldList) {  
  18.             System.out.println(field);  
  19.         }  
  20.   
  21.         client.close();  
  22.     }  
  23.   
  24.     private static List<String> getIndexFieldList(String fieldName,  
  25.             Map<String, Object> mapProperties) {  
  26.         List<String> fieldList = new ArrayList<String>();  
  27.         Map<String, Object> map = (Map<String, Object>) mapProperties  
  28.                 .get("properties");  
  29.         Set<String> keys = map.keySet();  
  30.         for (String key : keys) {  
  31.             if (((Map<String, Object>) map.get(key)).containsKey("type")) {  
  32.                 fieldList.add(fieldName + "" + key);  
  33.             } else {  
  34.                 List<String> tempList = getIndexFieldList(fieldName + "" + key  
  35.                         + ".", (Map<String, Object>) map.get(key));  
  36.                 fieldList.addAll(tempList);  
  37.             }  
  38.         }  
  39.         return fieldList;  
  40.     }  
  41.   
  42. }  
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
OSCHINA
登录后可查看更多优质内容
返回顶部
顶部