本文包含的內容java
1.安裝elasticsearch2.3.3linux
2.配置ik中文分詞器git
3.使用Java api 對document進行CRUDgithub
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
進入bin目錄
- cd elasticsearch-2.3.3/bin
啓動
若是能看到下面信息,說明成功了(每一個人的 名字多是不同的)
新開一個會話窗口,以前的那個用於啓動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分詞器。因此我就拿來用了。
按照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 先中止
再用 啓動
能看到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;
-
- public class GoodsFilter2ES {
- private String regionId;
-
- 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;
-
- public class ESUtils {
-
-
-
- private static final String host = "192.168.1.88";
-
-
- private static final int port = 9300;
-
-
- private static final ObjectMapper mapper = new ObjectMapper();
-
-
- private static Client getClient() throws UnknownHostException {
- Client client = TransportClient.builder().build()
- .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host), port));
- return client;
- }
-
-
- 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();
- }
-
- 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();
-
-
- 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));
- }
-
-
- 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();
- }
-
-
- 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;
- }
-
-
- 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();
- }
-
-
- public static void deleteDocument(String index, String type, Long goodsId) throws UnknownHostException {
- Client client = getClient();
-
- client.prepareDelete(index, type, goodsId+"").get();
-
- client.close();
- }
-
-
- public static void updateDocument(String index, String type, Goods goods)
- throws UnknownHostException, JsonProcessingException {
-
- addDocument(index, type, goods);
- }
-
- }
下面來寫單元測試看看結果(最後會放出測試類的全代碼)
- @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);
- }
上面的方法是 添加4個數據,而後生成索引
咱們在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{
-
- String[] r = {"r2","r3"};
- Goods goods = new Goods(5L, "新增的咖啡", r);
- ESUtils.addDocument("test_index", "goods", goods);
- }
junit執行成功後,在執行上面的查詢結果以下
說明成功了。 下面的修改和刪除我測試了是沒問題的。就不貼圖了。
最後發上測試的完整類
- 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 {
-
-
- @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);
- }
-
-
- @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);
- }
- }
-
-
- @Test
- public void testAddDoc() throws UnknownHostException, JsonProcessingException{
-
- String[] r = {"r2","r3"};
- Goods goods = new Goods(5L, "新增的咖啡", r);
- ESUtils.addDocument("test_index", "goods", goods);
- }
-
-
- @Test
- public void testUpdateDoc() throws UnknownHostException, JsonProcessingException{
- String[] r = {"r2","r3"};
- Goods goods = new Goods(5L, "修改啦的咖啡", r);
- ESUtils.updateDocument("test_index", "goods", goods);
- }
-
-
- @Test
- public void testDelDoc() throws UnknownHostException, JsonProcessingException{
- ESUtils.deleteDocument("test_index", "goods", 5L);
- }
- }
好啦,簡單的入門就到這裏了。其他的各位去官網
https://www.elastic.co 學習更多的東西吧。
代碼很簡單,就不上傳工程了。