转载自: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
- curl -L -O https://download.elastic.co/elasticsearch/release/org/elasticsearch/distribution/tar/elasticsearch/2.3.3/elasticsearch-2.3.3.tar.gz
- tar -xvf elasticsearch-2.3.3.tar.gz
- cd elasticsearch-2.3.3/bin
- ./elasticsearch
如果能看到下面信息,说明成功了(每个人的 名字可能是不一样的)

新开一个会话窗口,之前的那个用于启动es了。
检查节点健康
- 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 先停止
再用 启动
- ./elasticsearch

能看到ik字样,说明OK了。
3.使用java api 进行简单的 操作
新建一个maven工程
pom.xml
- <dependencies>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>4.11</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.elasticsearch</groupId>
- <artifactId>elasticsearch</artifactId>
- <version>2.3.3</version>
- </dependency>
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-databind</artifactId>
- <version>2.6.6</version>
- </dependency>
- </dependencies>
- package cn.lzg.esdemo;
- public class Goods {
- private Long id;
- private String name;
- private String[] regionIds;
- public Goods() {
- super();
- }
- public Goods(Long id, String name, String[] regionIds) {
- super();
- this.id = id;
- this.name = name;
- this.regionIds = regionIds;
- }
- 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[] getRegionIds() {
- return regionIds;
- }
- public void setRegionIds(String[] regionIds) {
- this.regionIds = regionIds;
- }
- @Override
- public String toString() {
- return id+" : " + name + " : "+regionIds;
- }
- }
- package cn.lzg.esdemo;
- /**
- * 用于es查询的dto
- *
- * @author lzg
- * @date 2016年6月12日
- */
- public class GoodsFilter2ES {
- private String regionId; // 园区UUID
- private String queryStr; // 条件
- public String getRegionId() {
- return regionId;
- }
- public void setRegionId(String regionId) {
- this.regionId = regionId;
- }
- public String getQueryStr() {
- return queryStr;
- }
- public void setQueryStr(String queryStr) {
- this.queryStr = queryStr;
- }
- }
这是用java api 对index document的简单的CRUD操作。
- package cn.lzg.esdemo;
- import java.io.IOException;
- import java.net.InetAddress;
- import java.net.UnknownHostException;
- import java.util.ArrayList;
- import java.util.List;
- import org.elasticsearch.action.bulk.BulkItemResponse;
- import org.elasticsearch.action.bulk.BulkRequestBuilder;
- import org.elasticsearch.action.bulk.BulkResponse;
- import org.elasticsearch.action.index.IndexRequest;
- import org.elasticsearch.action.search.SearchResponse;
- import org.elasticsearch.client.Client;
- import org.elasticsearch.client.transport.TransportClient;
- import org.elasticsearch.common.transport.InetSocketTransportAddress;
- import org.elasticsearch.index.query.BoolQueryBuilder;
- import org.elasticsearch.index.query.QueryBuilder;
- import org.elasticsearch.index.query.QueryBuilders;
- import org.elasticsearch.search.SearchHit;
- import com.fasterxml.jackson.core.JsonParseException;
- import com.fasterxml.jackson.core.JsonProcessingException;
- import com.fasterxml.jackson.databind.JsonMappingException;
- import com.fasterxml.jackson.databind.ObjectMapper;
- /**
- * elasticsearch 相关操作工具类
- *
- * @author lzg
- * @date 2016年6月12日
- */
- public class ESUtils {
- /**
- * es服务器的host
- */
- private static final String host = "192.168.1.88";
- /**
- * es服务器暴露给client的port
- */
- private static final int port = 9300;
- /**
- * jackson用于序列化操作的mapper
- */
- private static final ObjectMapper mapper = new ObjectMapper();
- /**
- * 获得连接
- *
- * @return
- * @throws UnknownHostException
- */
- private static Client getClient() throws UnknownHostException {
- Client client = TransportClient.builder().build()
- .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host), port));
- return client;
- }
- /**
- * 创建商品索引
- *
- * @param goodsList
- * 商品dto的列表
- * @throws UnknownHostException
- * @throws JsonProcessingException
- */
- public static void createIndex(List<Goods> goodsList) throws UnknownHostException, JsonProcessingException {
- Client client = getClient();
- // 如果存在就先删除索引
- if (client.admin().indices().prepareExists("test_index").get().isExists()) {
- client.admin().indices().prepareDelete("test_index").get();
- }
- // 创建索引,并设置mapping.
- String mappingStr = "{ \"goods\" : { \"properties\": { \"id\": { \"type\": \"long\" }, \"name\": {\"type\": \"string\", \"analyzer\": \"ik_max_word\"}, \"regionIds\": {\"type\": \"string\",\"index\": \"not_analyzed\"}}}}";
- client.admin().indices().prepareCreate("test_index").addMapping("goods", mappingStr).get();
- // 批量处理request
- BulkRequestBuilder bulkRequest = client.prepareBulk();
- byte[] json;
- for (Goods goods : goodsList) {
- json = mapper.writeValueAsBytes(goods);
- bulkRequest.add(new IndexRequest("test_index", "goods", goods.getId() + "").source(json));
- }
- // 执行批量处理request
- BulkResponse bulkResponse = bulkRequest.get();
- // 处理错误信息
- if (bulkResponse.hasFailures()) {
- System.out.println("====================批量创建索引过程中出现错误 下面是错误信息==========================");
- long count = 0L;
- for (BulkItemResponse bulkItemResponse : bulkResponse) {
- System.out.println("发生错误的 索引id为 : "+bulkItemResponse.getId()+" ,错误信息为:"+ bulkItemResponse.getFailureMessage());
- count++;
- }
- System.out.println("====================批量创建索引过程中出现错误 上面是错误信息 共有: "+count+" 条记录==========================");
- }
- client.close();
- }
- /**
- * 查询商品
- *
- * @param filter
- * @return
- * @throws JsonParseException
- * @throws JsonMappingException
- * @throws IOException
- */
- public static List<Goods> search(GoodsFilter2ES filter)
- throws JsonParseException, JsonMappingException, IOException {
- Client client = getClient();
- QueryBuilder qb = new BoolQueryBuilder()
- .must(QueryBuilders.matchQuery("name",filter.getQueryStr()))
- .must(QueryBuilders.termQuery("regionIds", filter.getRegionId()));
- SearchResponse response = client.prepareSearch("test_index").setTypes("goods").setQuery(qb).execute()
- .actionGet();
- SearchHit[] hits = response.getHits().getHits();
- List<Goods> goodsIds = new ArrayList<>();
- for (SearchHit hit : hits) {
- Goods goods = mapper.readValue(hit.getSourceAsString(), Goods.class);
- goodsIds.add(goods);
- }
- client.close();
- return goodsIds;
- }
- /**
- * 新增document
- *
- * @param index
- * 索引名称
- * @param type
- * 类型名称
- * @param goods
- * 商品dto
- * @throws UnknownHostException
- * @throws JsonProcessingException
- */
- public static void addDocument(String index, String type, Goods goods)
- throws UnknownHostException, JsonProcessingException {
- Client client = getClient();
- byte[] json = mapper.writeValueAsBytes(goods);
- client.prepareIndex(index, type, goods.getId() + "").setSource(json).get();
- client.close();
- }
- /**
- * 删除document
- *
- * @param index
- * 索引名称
- * @param type
- * 类型名称
- * @param goodsId
- * 要删除的商品id
- * @throws UnknownHostException
- */
- public static void deleteDocument(String index, String type, Long goodsId) throws UnknownHostException {
- Client client = getClient();
- client.prepareDelete(index, type, goodsId+"").get();
- client.close();
- }
- /**
- * 更新document
- *
- * @param index
- * 索引名称
- * @param type
- * 类型名称
- * @param goods
- * 商品dto
- * @throws JsonProcessingException
- * @throws UnknownHostException
- */
- public static void updateDocument(String index, String type, Goods goods)
- throws UnknownHostException, JsonProcessingException {
- //如果新增的时候index存在,就是更新操作
- addDocument(index, type, goods);
- }
- }
下面来写单元测试看看结果(最后会放出测试类的全代码)
上面的方法是 添加4个数据,然后生成索引
- @Test
- public void testCreatIndex() throws UnknownHostException, JsonProcessingException{
- List<Goods> goodsList = new ArrayList<>();
- String[] r123 = {"r1","r2","r3"};
- String[] r23 = {"r2","r3"};
- goodsList.add(new Goods(1L, "雀巢咖啡", r123));
- goodsList.add(new Goods(2L, "雀巢咖啡", r23));
- goodsList.add(new Goods(3L, "星巴克咖啡", r123));
- goodsList.add(new Goods(4L, "可口可乐", r123));
- ESUtils.createIndex(goodsList);
- }
我们在linux下 查看节点下的索引
'localhost:9200/_cat/indices?v'


发现有 test_index 这个索引了,而且索引下面是4个document。说明我们index构建成功。至于健康状态为yellow,是因为我们现在只有一个节点。他的数据没地方备份。准确的说法,大家去官网查看吧。大概是这个意思。
test查询
- @Test
- public void testSearch() throws JsonParseException, JsonMappingException, IOException{
- GoodsFilter2ES filter = new GoodsFilter2ES();
- filter.setQueryStr("咖啡");
- filter.setRegionId("r2");
- List<Goods> result = ESUtils.search(filter);
- for (Goods goods : result) {
- System.out.println(goods);
- }
- }
结果如下:


其他情况大家自己动手测试吧。
新增document
- @Test
- public void testAddDoc() throws UnknownHostException, JsonProcessingException{
- //test_index 和 goods 在创建索引的时候写死了 所以这样 就传这两个值
- String[] r = {"r2","r3"};
- Goods goods = new Goods(5L, "新增的咖啡", r);
- ESUtils.addDocument("test_index", "goods", goods);
- }

说明成功了。 下面的修改和删除我测试了是没问题的。就不贴图了。
最后发上测试的完整类
- package cn.lzg.esdemo;
- import java.io.IOException;
- import java.net.UnknownHostException;
- import java.util.ArrayList;
- import java.util.List;
- import org.junit.Test;
- import com.fasterxml.jackson.core.JsonParseException;
- import com.fasterxml.jackson.core.JsonProcessingException;
- import com.fasterxml.jackson.databind.JsonMappingException;
- public class MyTest {
- /**
- * 生成索引
- * @throws UnknownHostException
- * @throws JsonProcessingException
- */
- @Test
- public void testCreatIndex() throws UnknownHostException, JsonProcessingException{
- List<Goods> goodsList = new ArrayList<>();
- String[] r123 = {"r1","r2","r3"};
- String[] r23 = {"r2","r3"};
- goodsList.add(new Goods(1L, "雀巢咖啡", r123));
- goodsList.add(new Goods(2L, "雅哈咖啡", r23));
- goodsList.add(new Goods(3L, "星巴克咖啡", r123));
- goodsList.add(new Goods(4L, "可口可乐", r123));
- ESUtils.createIndex(goodsList);
- }
- /**
- * 测试search
- * @throws JsonParseException
- * @throws JsonMappingException
- * @throws IOException
- */
- @Test
- public void testSearch() throws JsonParseException, JsonMappingException, IOException{
- GoodsFilter2ES filter = new GoodsFilter2ES();
- filter.setQueryStr("咖啡");
- filter.setRegionId("r2");
- List<Goods> result = ESUtils.search(filter);
- for (Goods goods : result) {
- System.out.println(goods);
- }
- }
- /**
- * 测试新增doc
- * @throws UnknownHostException
- * @throws JsonProcessingException
- */
- @Test
- public void testAddDoc() throws UnknownHostException, JsonProcessingException{
- //test_index 和 goods 在创建索引的时候写死了 所以这样 就传这两个值
- String[] r = {"r2","r3"};
- Goods goods = new Goods(5L, "新增的咖啡", r);
- ESUtils.addDocument("test_index", "goods", goods);
- }
- /**
- * 测试修改doc
- * @throws UnknownHostException
- * @throws JsonProcessingException
- */
- @Test
- public void testUpdateDoc() throws UnknownHostException, JsonProcessingException{
- String[] r = {"r2","r3"};
- Goods goods = new Goods(5L, "修改啦的咖啡", r);
- ESUtils.updateDocument("test_index", "goods", goods);
- }
- /**
- * 测试删除doc
- * @throws UnknownHostException
- * @throws JsonProcessingException
- */
- @Test
- public void testDelDoc() throws UnknownHostException, JsonProcessingException{
- ESUtils.deleteDocument("test_index", "goods", 5L);
- }
- }
好啦,简单的入门就到这里了。其余的各位去官网 https://www.elastic.co 学习更多的东西吧。
代码很简单,就不上传工程了。