Elasticsearch之Java客户端Jest

1、是什么

它是Elasticsearch的Java HTTP Rest客户端。

2、实例

(1)User.java

public class User {

	@JestId
	private Integer id;
	private String name;
	private Date birth;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Date getBirth() {
		return birth;
	}
	public void setBirth(Date birth) {
		this.birth = birth;
	}
	public User() {
		super();
		// TODO Auto-generated constructor stub
	}
	public User(Integer id, String name, Date birth) {
		super();
		this.id = id;
		this.name = name;
		this.birth = birth;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", birth=" + birth + "]";
	}
}

(2)JestService.java

public class JestService {

	/**
	 * 获取JestClient对象
	 * @return
	 */
	public JestClient getJestClient() {  
			
	    JestClientFactory factory = new JestClientFactory();
	    factory.setHttpClientConfig(new HttpClientConfig
	                           .Builder("http://localhost:9200")
	                           .gson(new GsonBuilder().setDateFormat("yyyy-MM-dd'T'hh:mm:ss").create())
	                           .connTimeout(1500)
	                           .readTimeout(3000)
	                           .multiThreaded(true)
	                           .build());
	    return factory.getObject();
        }
	
	/**
	 * 创建索引
	 * @param jestClient
	 * @param indexName
	 * @return
	 * @throws Exception
	 */
	public boolean createIndex(JestClient jestClient, String indexName) throws Exception {
	    
	    JestResult jr = jestClient.execute(new CreateIndex.Builder(indexName).build());
	    return jr.isSucceeded();
	}
	
	/**
	 * Put映射
	 * @param jestClient
	 * @param indexName
	 * @param typeName
	 * @param source
	 * @return
	 * @throws Exception
	 */
	public boolean createIndexMapping(JestClient jestClient, String indexName, String typeName, String source) throws Exception {

	    PutMapping putMapping = new PutMapping.Builder(indexName, typeName, source).build();
	    JestResult jr = jestClient.execute(putMapping);
	    return jr.isSucceeded();
        }
	
	/**
	 * Get映射
	 * @param jestClient
	 * @param indexName
	 * @param typeName
	 * @return
	 * @throws Exception
	 */
	public String getIndexMapping(JestClient jestClient, String indexName, String typeName) throws Exception {

	    GetMapping getMapping = new GetMapping.Builder().addIndex(indexName).addType(typeName).build();
	    JestResult jr = jestClient.execute(getMapping);
	    return jr.getJsonString();
        }
	
	/**
	 * 索引文档
	 * @param jestClient
	 * @param indexName
	 * @param typeName
	 * @param objs
	 * @return
	 * @throws Exception
	 */
	public boolean index(JestClient jestClient, String indexName, String typeName, List<Object> objs) throws Exception {
	    
	    Bulk.Builder bulk = new Bulk.Builder().defaultIndex(indexName).defaultType(typeName);
	    for (Object obj : objs) {
	      Index index = new Index.Builder(obj).build();
	      bulk.addAction(index);
	    }
	    BulkResult br = jestClient.execute(bulk.build());
	    return br.isSucceeded();
        }
	
	/**
	 * 搜索文档
	 * @param jestClient
	 * @param indexName
	 * @param typeName
	 * @param query
	 * @return
	 * @throws Exception
	 */
	public SearchResult search(JestClient jestClient, String indexName, String typeName, String query) throws Exception {
	    
	    Search search = new Search.Builder(query)
	        .addIndex(indexName)
	        .addType(typeName)
	        .build();
	    return jestClient.execute(search);
        }
	
	/**
	 * Count文档
	 * @param jestClient
	 * @param indexName
	 * @param typeName
	 * @param query
	 * @return
	 * @throws Exception
	 */
	public Double count(JestClient jestClient, String indexName, String typeName, String query) throws Exception {

	    Count count = new Count.Builder()
	        .addIndex(indexName)
	        .addType(typeName)
	        .query(query)
	        .build();
	    CountResult results = jestClient.execute(count); 
	    return results.getCount();
	}
	
	/**
	 * Get文档
	 * @param jestClient
	 * @param indexName
	 * @param typeName
	 * @param id
	 * @return
	 * @throws Exception
	 */
	public JestResult get(JestClient jestClient, String indexName, String typeName, String id) throws Exception {
		  
	    Get get = new Get.Builder(indexName, id).type(typeName).build();
	    return jestClient.execute(get);
	}
	
	/**
	 * Delete索引
	 * @param jestClient
	 * @param indexName
	 * @return
	 * @throws Exception
	 */
	public boolean delete(JestClient jestClient, String indexName) throws Exception {

	    JestResult jr = jestClient.execute(new DeleteIndex.Builder(indexName).build());
	    return jr.isSucceeded();
	}
	
	/**
	 * Delete文档
	 * @param jestClient
	 * @param indexName
	 * @param typeName
	 * @param id
	 * @return
	 * @throws Exception
	 */
	public boolean delete(JestClient jestClient, String indexName, String typeName, String id) throws Exception {
	    
	    DocumentResult dr = jestClient.execute(new Delete.Builder(id).index(indexName).type(typeName).build());
	    return dr.isSucceeded();
	}
	
	/**
	 * 关闭JestClient客户端
	 * @param jestClient
	 * @throws Exception
	 */
	public void closeJestClient(JestClient jestClient) throws Exception {
	    
	    if (jestClient != null) {
	      jestClient.shutdownClient();
	    }
        }
}
(3)UserTest.java

public class UserTest {

	private JestService jestService;
        private JestClient jestClient;
        private String indexName = "hwd";
        private String typeName = "user";
	  
	@Before
	public void setUp() throws Exception {
		
	    jestService = new JestService();
	    jestClient = jestService.getJestClient();
	}

	@After
	public void tearDown() throws Exception {
		
	    jestService.closeJestClient(jestClient);
	}

	@Test
        public void createIndex() throws Exception {
    
	    boolean result = jestService.createIndex(jestClient, indexName);
	    System.out.println(result);
        }
	
	@Test
        public void createIndexMapping() throws Exception {
    
	    String source = "{\"" + typeName + "\":{\"properties\":{"
						+ "\"id\":{\"type\":\"integer\"}"
						+ ",\"name\":{\"type\":\"string\",\"index\":\"not_analyzed\"}"
						+ ",\"birth\":{\"type\":\"date\",\"format\":\"strict_date_optional_time||epoch_millis\"}"
						+ "}}}";
            System.out.println(source);
            boolean result = jestService.createIndexMapping(jestClient, indexName, typeName, source);
            System.out.println(result);
        }
	
	@Test
	public void getIndexMapping() throws Exception {
	    
	    String result = jestService.getIndexMapping(jestClient, indexName, typeName);
	    System.out.println(result);
	}
	
	@Test
	public void index() throws Exception {
		
	    List<Object> objs = new ArrayList<Object>();
	    objs.add(new User(1, "T:o\"m-", new Date()));
	    objs.add(new User(2, "J,e{r}r;y:", new Date()));
	    boolean result = jestService.index(jestClient, indexName, typeName, objs);
	    System.out.println(result);
	}
	
	@Test
	public void termQuery() throws Exception {
	    
	    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
	    QueryBuilder queryBuilder = QueryBuilders
	        .termQuery("name", "T:o\"m-");//单值完全匹配查询
	    searchSourceBuilder.query(queryBuilder);
	    searchSourceBuilder.size(10);
	    searchSourceBuilder.from(0);
	    String query = searchSourceBuilder.toString(); 
	    System.out.println(query);
	    SearchResult result = jestService.search(jestClient, indexName, typeName, query);
	    List<Hit<User, Void>> hits = result.getHits(User.class);
	    System.out.println("Size:" + hits.size());
	    for (Hit<User, Void> hit : hits) {
	      User user = hit.source;
	      System.out.println(user.toString());
	    }
	}
	  
	@Test
	public void termsQuery() throws Exception {
	    
	    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
	    QueryBuilder queryBuilder = QueryBuilders
	        .termsQuery("name", new String[]{ "T:o\"m-", "J,e{r}r;y:" });//多值完全匹配查询
	    searchSourceBuilder.query(queryBuilder);
	    searchSourceBuilder.size(10);
	    searchSourceBuilder.from(0);
	    String query = searchSourceBuilder.toString(); 
	    System.out.println(query);
	    SearchResult result = jestService.search(jestClient, indexName, typeName, query);
	    List<Hit<User, Void>> hits = result.getHits(User.class);
	    System.out.println("Size:" + hits.size());
	    for (Hit<User, Void> hit : hits) {
	      User user = hit.source;
	      System.out.println(user.toString());
	    }
	}
	  
	@Test
	public void wildcardQuery() throws Exception {
	    
	    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
	    QueryBuilder queryBuilder = QueryBuilders
	        .wildcardQuery("name", "*:*");//通配符和正则表达式查询
	    searchSourceBuilder.query(queryBuilder);
	    searchSourceBuilder.size(10);
	    searchSourceBuilder.from(0);
	    String query = searchSourceBuilder.toString();    
	    System.out.println(query);
	    SearchResult result = jestService.search(jestClient, indexName, typeName, query);
	    List<Hit<User, Void>> hits = result.getHits(User.class);
	    System.out.println("Size:" + hits.size());
	    for (Hit<User, Void> hit : hits) {
	      User user = hit.source;
	      System.out.println(user.toString());
	    }
	}
	  
	@Test
	public void prefixQuery() throws Exception {
	    
	    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
	    QueryBuilder queryBuilder = QueryBuilders
	        .prefixQuery("name", "T:o");//前缀查询
	    searchSourceBuilder.query(queryBuilder);
	    searchSourceBuilder.size(10);
	    searchSourceBuilder.from(0);
	    String query = searchSourceBuilder.toString();    
	    System.out.println(query);
	    SearchResult result = jestService.search(jestClient, indexName, typeName, query);
	    List<Hit<User, Void>> hits = result.getHits(User.class);
	    System.out.println("Size:" + hits.size());
	    for (Hit<User, Void> hit : hits) {
	      User user = hit.source;
	      System.out.println(user.toString());
	    }
	}
	  
	@Test
	public void rangeQuery() throws Exception {
	    
	    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
	    QueryBuilder queryBuilder = QueryBuilders
	        .rangeQuery("birth")
	        .gte("2016-09-01T00:00:00")
	        .lte("2016-10-01T00:00:00")
	        .includeLower(true)
	        .includeUpper(true);//区间查询
	    searchSourceBuilder.query(queryBuilder);
	    searchSourceBuilder.size(10);
	    searchSourceBuilder.from(0);
	    String query = searchSourceBuilder.toString();
	    System.out.println(query);
	    SearchResult result = jestService.search(jestClient, indexName, typeName, query);
	    List<Hit<User, Void>> hits = result.getHits(User.class);
	    System.out.println("Size:" + hits.size());
	    for (Hit<User, Void> hit : hits) {
	      User user = hit.source;
	      System.out.println(user.toString());
	    }
	}
	  
	@Test
	public void queryString() throws Exception {
	    
	    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
	    QueryBuilder queryBuilder = QueryBuilders
	        .queryString(QueryParser.escape("T:o\""));//文本检索,应该是将查询的词先分成词库中存在的词,然后分别去检索,存在任一存在的词即返回,查询词分词后是OR的关系。需要转义特殊字符
	    searchSourceBuilder.query(queryBuilder);
	    searchSourceBuilder.size(10);
	    searchSourceBuilder.from(0);
	    String query = searchSourceBuilder.toString(); 
	    System.out.println(query);
	    SearchResult result = jestService.search(jestClient, indexName, typeName, query);
	    List<Hit<User, Void>> hits = result.getHits(User.class);
	    System.out.println("Size:" + hits.size());
	    for (Hit<User, Void> hit : hits) {
	      User user = hit.source;
	      System.out.println(user.toString());
	    }
	}
	  
	@Test
	public void count() throws Exception {
	    
	    String[] name = new String[]{ "T:o\"m-", "Jerry" };
	    String from = "2016-09-01T00:00:00";
	    String to = "2016-10-01T00:00:00";
	    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
	    QueryBuilder queryBuilder = QueryBuilders.boolQuery()
	        .must(QueryBuilders.termsQuery("name", name))
	        .must(QueryBuilders.rangeQuery("birth").gte(from).lte(to));
	    searchSourceBuilder.query(queryBuilder);
	    String query = searchSourceBuilder.toString(); 
	    System.out.println(query);
	    Double count = jestService.count(jestClient, indexName, typeName, query);
	    System.out.println("Count:" + count);
	}
	  
	@Test
	public void get() throws Exception {
	    
	    String id = "2";
	    JestResult result = jestService.get(jestClient, indexName, typeName, id);
	    if (result.isSucceeded()) {
	      User user = result.getSourceAsObject(User.class);
	      System.out.println(user.toString());
	    }
	}
	    
	@Test
	public void deleteIndexDocument() throws Exception {
	    
	    String id = "2";
	    boolean result = jestService.delete(jestClient, indexName, typeName, id);
	    System.out.println(result);
	}
	
	@Test
	public void deleteIndex() throws Exception {
	    
	    boolean result = jestService.delete(jestClient, indexName);
	    System.out.println(result);
	}
}

评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值