elasticsearch2.3.3 java client demo

转载自:http://blog.csdn.net/hunanlzg/article/details/51658370

本文包含的内容

1.安装elasticsearch2.3.3

2.配置ik中文分词器

3.使用Java api 对document进行CRUD


1.安装

建议在linux 下(如果是windows直接去https://www.elastic.co/downloads/elasticsearch下载 zip包也可以)
下面以linux环境为例子

因为es不能跑在root下面,所以我们要自己新建一个用户。这个我就不多说了。
还有就是避免下面出现一些权限问题,可以考虑 直接 chmod -R 777 elasticsearch-2.3.3 反正是学习,先上手在说。

安装es
  1. curl -L -O https://download.elastic.co/elasticsearch/release/org/elasticsearch/distribution/tar/elasticsearch/2.3.3/elasticsearch-2.3.3.tar.gz  
解压
  1. tar -xvf elasticsearch-2.3.3.tar.gz  
进入bin目录
  1. cd elasticsearch-2.3.3/bin  
启动
  1. ./elasticsearch  

如果能看到下面信息,说明成功了(每个人的 名字可能是不一样的)

新开一个会话窗口,之前的那个用于启动es了。
检查节点健康
  1. curl 'localhost:9200/_cat/health?v'  

stauts 是绿色说明OK。
进过上面的步骤,es已经安装并且运行起来了。

但是现在是在虚拟机中的Linux运行的。直接访问  你的ip:9200  应该是打开不了的。
需要在 
/es根目录/config/elasticsearch.yml  的最后面加上
network.host: 0.0.0.0

重启在访问  你的ip:9200  应该就能看到一个简单的网页了。

记得 关闭linux的防火墙哦(学习的时候这样简单粗暴点。)

2.配置ik中文分词器

因为要用es来进行全文检索,所以对应的中文分词器也不能少了。问了很多人都是推荐使用ik分词器。所以我就拿来用了。
已经有大神将ik封装成了es的一个插件  git 地址: https://github.com/medcl/elasticsearch-analysis-ik

按照git上面的步骤(建议大家看下,用不了几分钟的)
将git项目 下载下来 mvn package 一下。
拿到 target/releases/elasticsearch-analysis-ik-2.3.3.zip 下的zip包 放到你刚刚 安装 es的 根目录下的 plugins/ik 文件夹中。
默认没有ik文件夹,我们需要自己建一个。
然后 解压 unzip elasticsearch-analysis-ik-2.3.3.zip
结果如下:


重启es
其实就是 ctrl+c 先停止
再用 启动
  1. ./elasticsearch  

能看到ik字样,说明OK了。

3.使用java api 进行简单的 操作

新建一个maven工程
pom.xml
  1.  <dependencies>  
  2.    <dependency>  
  3.      <groupId>junit</groupId>  
  4.      <artifactId>junit</artifactId>  
  5.      <version>4.11</version>  
  6.      <scope>test</scope>  
  7.    </dependency>  
  8.    <dependency>  
  9.     <groupId>org.elasticsearch</groupId>  
  10.     <artifactId>elasticsearch</artifactId>  
  11.     <version>2.3.3</version>  
  12. </dependency>  
  13.   
  14. <dependency>  
  15.     <groupId>com.fasterxml.jackson.core</groupId>  
  16.     <artifactId>jackson-databind</artifactId>  
  17.     <version>2.6.6</version>  
  18. </dependency>  
  19.   
  20.  </dependencies>  

一共三个类,如下

  1. package cn.lzg.esdemo;  
  2.   
  3. public class Goods {  
  4.     private Long id;  
  5.     private String name;  
  6.     private String[] regionIds;  
  7.       
  8.     public Goods() {  
  9.         super();  
  10.     }  
  11.       
  12.     public Goods(Long id, String name, String[] regionIds) {  
  13.         super();  
  14.         this.id = id;  
  15.         this.name = name;  
  16.         this.regionIds = regionIds;  
  17.     }  
  18.   
  19.     public Long getId() {  
  20.         return id;  
  21.     }  
  22.     public void setId(Long id) {  
  23.         this.id = id;  
  24.     }  
  25.     public String getName() {  
  26.         return name;  
  27.     }  
  28.     public void setName(String name) {  
  29.         this.name = name;  
  30.     }  
  31.   
  32.     public String[] getRegionIds() {  
  33.         return regionIds;  
  34.     }  
  35.   
  36.     public void setRegionIds(String[] regionIds) {  
  37.         this.regionIds = regionIds;  
  38.     }  
  39.   
  40.   
  41.     @Override  
  42.     public String toString() {  
  43.         return id+" : " + name + " : "+regionIds;  
  44.     }  
  45. }  


  1. package cn.lzg.esdemo;  
  2.   
  3. /** 
  4.  * 用于es查询的dto 
  5.  *  
  6.  * @author lzg 
  7.  * @date 2016年6月12日 
  8.  */  
  9. public class GoodsFilter2ES {  
  10.     private String regionId; // 园区UUID  
  11.   
  12.     private String queryStr; // 条件  
  13.   
  14.     public String getRegionId() {  
  15.         return regionId;  
  16.     }  
  17.   
  18.     public void setRegionId(String regionId) {  
  19.         this.regionId = regionId;  
  20.     }  
  21.   
  22.     public String getQueryStr() {  
  23.         return queryStr;  
  24.     }  
  25.   
  26.     public void setQueryStr(String queryStr) {  
  27.         this.queryStr = queryStr;  
  28.     }  
  29. }  


这是用java api 对index document的简单的CRUD操作。
  1. package cn.lzg.esdemo;  
  2.   
  3. import java.io.IOException;  
  4. import java.net.InetAddress;  
  5. import java.net.UnknownHostException;  
  6. import java.util.ArrayList;  
  7. import java.util.List;  
  8.   
  9. import org.elasticsearch.action.bulk.BulkItemResponse;  
  10. import org.elasticsearch.action.bulk.BulkRequestBuilder;  
  11. import org.elasticsearch.action.bulk.BulkResponse;  
  12. import org.elasticsearch.action.index.IndexRequest;  
  13. import org.elasticsearch.action.search.SearchResponse;  
  14. import org.elasticsearch.client.Client;  
  15. import org.elasticsearch.client.transport.TransportClient;  
  16. import org.elasticsearch.common.transport.InetSocketTransportAddress;  
  17. import org.elasticsearch.index.query.BoolQueryBuilder;  
  18. import org.elasticsearch.index.query.QueryBuilder;  
  19. import org.elasticsearch.index.query.QueryBuilders;  
  20. import org.elasticsearch.search.SearchHit;  
  21.   
  22. import com.fasterxml.jackson.core.JsonParseException;  
  23. import com.fasterxml.jackson.core.JsonProcessingException;  
  24. import com.fasterxml.jackson.databind.JsonMappingException;  
  25. import com.fasterxml.jackson.databind.ObjectMapper;  
  26.   
  27. /** 
  28.  * elasticsearch 相关操作工具类 
  29.  *  
  30.  * @author lzg 
  31.  * @date 2016年6月12日 
  32.  */  
  33. public class ESUtils {  
  34.   
  35.   
  36.     /** 
  37.      * es服务器的host 
  38.      */  
  39.     private static final String host = "192.168.1.88";  
  40.   
  41.     /** 
  42.      * es服务器暴露给client的port 
  43.      */  
  44.     private static final int port = 9300;  
  45.   
  46.     /** 
  47.      * jackson用于序列化操作的mapper 
  48.      */  
  49.     private static final ObjectMapper mapper = new ObjectMapper();  
  50.   
  51.     /** 
  52.      * 获得连接 
  53.      *  
  54.      * @return 
  55.      * @throws UnknownHostException 
  56.      */  
  57.     private static Client getClient() throws UnknownHostException {  
  58.         Client client = TransportClient.builder().build()  
  59.                 .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host), port));  
  60.         return client;  
  61.     }  
  62.   
  63.     /** 
  64.      * 创建商品索引 
  65.      *  
  66.      * @param goodsList 
  67.      *            商品dto的列表 
  68.      * @throws UnknownHostException 
  69.      * @throws JsonProcessingException 
  70.      */  
  71.     public static void createIndex(List<Goods> goodsList) throws UnknownHostException, JsonProcessingException {  
  72.         Client client = getClient();  
  73.         // 如果存在就先删除索引  
  74.         if (client.admin().indices().prepareExists("test_index").get().isExists()) {  
  75.             client.admin().indices().prepareDelete("test_index").get();  
  76.         }  
  77.         // 创建索引,并设置mapping.  
  78.         String mappingStr = "{ \"goods\" : { \"properties\": { \"id\": { \"type\": \"long\" }, \"name\": {\"type\": \"string\", \"analyzer\": \"ik_max_word\"}, \"regionIds\": {\"type\": \"string\",\"index\": \"not_analyzed\"}}}}";  
  79.         client.admin().indices().prepareCreate("test_index").addMapping("goods", mappingStr).get();  
  80.   
  81.         // 批量处理request  
  82.         BulkRequestBuilder bulkRequest = client.prepareBulk();  
  83.   
  84.         byte[] json;  
  85.         for (Goods goods : goodsList) {  
  86.             json = mapper.writeValueAsBytes(goods);  
  87.             bulkRequest.add(new IndexRequest("test_index", "goods", goods.getId() + "").source(json));  
  88.         }  
  89.   
  90.         // 执行批量处理request  
  91.         BulkResponse bulkResponse = bulkRequest.get();  
  92.   
  93.         // 处理错误信息  
  94.         if (bulkResponse.hasFailures()) {  
  95.             System.out.println("====================批量创建索引过程中出现错误 下面是错误信息==========================");  
  96.             long count = 0L;  
  97.             for (BulkItemResponse bulkItemResponse : bulkResponse) {  
  98.                 System.out.println("发生错误的 索引id为 : "+bulkItemResponse.getId()+" ,错误信息为:"+ bulkItemResponse.getFailureMessage());  
  99.                 count++;  
  100.             }  
  101.             System.out.println("====================批量创建索引过程中出现错误 上面是错误信息 共有: "+count+" 条记录==========================");  
  102.         }  
  103.   
  104.         client.close();  
  105.     }  
  106.   
  107.     /** 
  108.      * 查询商品 
  109.      *  
  110.      * @param filter 
  111.      * @return 
  112.      * @throws JsonParseException 
  113.      * @throws JsonMappingException 
  114.      * @throws IOException 
  115.      */  
  116.     public static List<Goods> search(GoodsFilter2ES filter)  
  117.             throws JsonParseException, JsonMappingException, IOException {  
  118.         Client client = getClient();  
  119.         QueryBuilder qb = new BoolQueryBuilder()  
  120.                 .must(QueryBuilders.matchQuery("name",filter.getQueryStr()))  
  121.                 .must(QueryBuilders.termQuery("regionIds", filter.getRegionId()));  
  122.   
  123.         SearchResponse response = client.prepareSearch("test_index").setTypes("goods").setQuery(qb).execute()  
  124.                 .actionGet();  
  125.   
  126.         SearchHit[] hits = response.getHits().getHits();  
  127.         List<Goods> goodsIds = new ArrayList<>();  
  128.         for (SearchHit hit : hits) {  
  129.             Goods goods = mapper.readValue(hit.getSourceAsString(), Goods.class);  
  130.             goodsIds.add(goods);  
  131.         }  
  132.   
  133.         client.close();  
  134.         return goodsIds;  
  135.     }  
  136.   
  137.     /** 
  138.      * 新增document 
  139.      *  
  140.      * @param index 
  141.      *            索引名称 
  142.      * @param type 
  143.      *            类型名称 
  144.      * @param goods 
  145.      *            商品dto 
  146.      * @throws UnknownHostException 
  147.      * @throws JsonProcessingException 
  148.      */  
  149.     public static void addDocument(String index, String type, Goods goods)  
  150.             throws UnknownHostException, JsonProcessingException {  
  151.         Client client = getClient();  
  152.   
  153.         byte[] json = mapper.writeValueAsBytes(goods);  
  154.   
  155.         client.prepareIndex(index, type, goods.getId() + "").setSource(json).get();  
  156.   
  157.         client.close();  
  158.     }  
  159.   
  160.     /** 
  161.      * 删除document 
  162.      *  
  163.      * @param index 
  164.      *            索引名称 
  165.      * @param type 
  166.      *            类型名称 
  167.      * @param goodsId 
  168.      *            要删除的商品id 
  169.      * @throws UnknownHostException 
  170.      */  
  171.     public static void deleteDocument(String index, String type, Long goodsId) throws UnknownHostException {  
  172.         Client client = getClient();  
  173.   
  174.         client.prepareDelete(index, type, goodsId+"").get();  
  175.   
  176.         client.close();  
  177.     }  
  178.   
  179.     /** 
  180.      * 更新document 
  181.      *  
  182.      * @param index 
  183.      *            索引名称 
  184.      * @param type 
  185.      *            类型名称 
  186.      * @param goods 
  187.      *            商品dto 
  188.      * @throws JsonProcessingException 
  189.      * @throws UnknownHostException 
  190.      */  
  191.     public static void updateDocument(String index, String type, Goods goods)  
  192.             throws UnknownHostException, JsonProcessingException {  
  193.         //如果新增的时候index存在,就是更新操作  
  194.         addDocument(index, type, goods);  
  195.     }  
  196.   
  197. }  



下面来写单元测试看看结果(最后会放出测试类的全代码)
  1. @Test  
  2.     public void testCreatIndex() throws UnknownHostException, JsonProcessingException{  
  3.         List<Goods> goodsList = new ArrayList<>();  
  4.           
  5.         String[] r123 = {"r1","r2","r3"};  
  6.         String[] r23 = {"r2","r3"};  
  7.         goodsList.add(new Goods(1L, "雀巢咖啡", r123));  
  8.         goodsList.add(new Goods(2L, "雀巢咖啡", r23));  
  9.           
  10.         goodsList.add(new Goods(3L, "星巴克咖啡", r123));  
  11.         goodsList.add(new Goods(4L, "可口可乐", r123));  
  12.           
  13.         ESUtils.createIndex(goodsList);  
  14.     }  
上面的方法是 添加4个数据,然后生成索引


我们在linux下 查看节点下的索引
'localhost:9200/_cat/indices?v'


发现有 test_index 这个索引了,而且索引下面是4个document。说明我们index构建成功。至于健康状态为yellow,是因为我们现在只有一个节点。他的数据没地方备份。准确的说法,大家去官网查看吧。大概是这个意思。


test查询
  1. @Test  
  2.     public void testSearch() throws JsonParseException, JsonMappingException, IOException{  
  3.         GoodsFilter2ES filter = new GoodsFilter2ES();  
  4.         filter.setQueryStr("咖啡");  
  5.         filter.setRegionId("r2");  
  6.         List<Goods> result = ESUtils.search(filter);  
  7.         for (Goods goods : result) {  
  8.             System.out.println(goods);  
  9.         }  
  10.     }  

结果如下:


其他情况大家自己动手测试吧。

新增document
  1. @Test  
  2.     public void testAddDoc() throws UnknownHostException, JsonProcessingException{  
  3.         //test_index 和 goods 在创建索引的时候写死了 所以这样 就传这两个值  
  4.         String[] r = {"r2","r3"};  
  5.         Goods goods = new Goods(5L, "新增的咖啡", r);  
  6.         ESUtils.addDocument("test_index", "goods", goods);  
  7.     }  
junit执行成功后,在执行上面的查询结果如下

说明成功了。 下面的修改和删除我测试了是没问题的。就不贴图了。

最后发上测试的完整类

  1. package cn.lzg.esdemo;  
  2.   
  3. import java.io.IOException;  
  4. import java.net.UnknownHostException;  
  5. import java.util.ArrayList;  
  6. import java.util.List;  
  7.   
  8. import org.junit.Test;  
  9.   
  10. import com.fasterxml.jackson.core.JsonParseException;  
  11. import com.fasterxml.jackson.core.JsonProcessingException;  
  12. import com.fasterxml.jackson.databind.JsonMappingException;  
  13.   
  14. public class MyTest {  
  15.       
  16.     /** 
  17.      * 生成索引 
  18.      * @throws UnknownHostException 
  19.      * @throws JsonProcessingException 
  20.      */  
  21.     @Test  
  22.     public void testCreatIndex() throws UnknownHostException, JsonProcessingException{  
  23.         List<Goods> goodsList = new ArrayList<>();  
  24.           
  25.         String[] r123 = {"r1","r2","r3"};  
  26.         String[] r23 = {"r2","r3"};  
  27.         goodsList.add(new Goods(1L, "雀巢咖啡", r123));  
  28.         goodsList.add(new Goods(2L, "雅哈咖啡", r23));  
  29.           
  30.         goodsList.add(new Goods(3L, "星巴克咖啡", r123));  
  31.         goodsList.add(new Goods(4L, "可口可乐", r123));  
  32.           
  33.         ESUtils.createIndex(goodsList);  
  34.     }  
  35.       
  36.     /** 
  37.      * 测试search 
  38.      * @throws JsonParseException 
  39.      * @throws JsonMappingException 
  40.      * @throws IOException 
  41.      */  
  42.     @Test  
  43.     public void testSearch() throws JsonParseException, JsonMappingException, IOException{  
  44.         GoodsFilter2ES filter = new GoodsFilter2ES();  
  45.         filter.setQueryStr("咖啡");  
  46.         filter.setRegionId("r2");  
  47.         List<Goods> result = ESUtils.search(filter);  
  48.         for (Goods goods : result) {  
  49.             System.out.println(goods);  
  50.         }  
  51.     }  
  52.       
  53.     /** 
  54.      * 测试新增doc 
  55.      * @throws UnknownHostException 
  56.      * @throws JsonProcessingException 
  57.      */  
  58.     @Test  
  59.     public void testAddDoc() throws UnknownHostException, JsonProcessingException{  
  60.         //test_index 和 goods 在创建索引的时候写死了 所以这样 就传这两个值  
  61.         String[] r = {"r2","r3"};  
  62.         Goods goods = new Goods(5L, "新增的咖啡", r);  
  63.         ESUtils.addDocument("test_index", "goods", goods);  
  64.     }  
  65.       
  66.     /** 
  67.      * 测试修改doc 
  68.      * @throws UnknownHostException 
  69.      * @throws JsonProcessingException 
  70.      */  
  71.     @Test  
  72.     public void testUpdateDoc() throws UnknownHostException, JsonProcessingException{  
  73.         String[] r = {"r2","r3"};  
  74.         Goods goods = new Goods(5L, "修改啦的咖啡", r);  
  75.         ESUtils.updateDocument("test_index", "goods", goods);  
  76.     }  
  77.       
  78.     /** 
  79.      * 测试删除doc 
  80.      * @throws UnknownHostException 
  81.      * @throws JsonProcessingException 
  82.      */  
  83.     @Test  
  84.     public void testDelDoc() throws UnknownHostException, JsonProcessingException{  
  85.         ESUtils.deleteDocument("test_index", "goods", 5L);  
  86.     }  
  87. }  

好啦,简单的入门就到这里了。其余的各位去官网  https://www.elastic.co 学习更多的东西吧。
代码很简单,就不上传工程了。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值