搜索學(xué)習(xí)--Elasticsearch全文搜索服務(wù)器的基本使用

前言

之前我們使用Solr全文搜索服務(wù)器來建立我們自己的搜索竹椒,本篇文章將介紹跟Solr類似的另一種搜索服務(wù)器——Elasticsearch滑废。就個人而言,Elasticsearch比Solr使用更方便竟痰,只要使用Http通過Json傳輸就可以去使用了盘榨。對于ElasticSearch服務(wù)器的部署,分布式朴译,集群這里就先不介紹了井佑。部署啟動后,訪問 http://127.0.0.1:9200/眠寿,顯示如下類似信息躬翁,說明服務(wù)器已經(jīng)起來了。
> {
"name" : "8n5uD4P",
"cluster_name" : "elasticsearch",
"cluster_uuid" : "D-hKMOfgQQKjizry-i41qw",
"version" : {
"number" : "6.0.0",
"build_hash" : "8f0685b",
"build_date" : "2017-11-10T18:41:22.859Z",
"build_snapshot" : false,
"lucene_version" : "7.0.1",
"minimum_wire_compatibility_version" : "5.6.0",
"minimum_index_compatibility_version" : "5.0.0"
},
"tagline" : "You Know, for Search"
}
接下來就是通過客戶端去調(diào)用了盯拱,這里使用Java

依賴

 <dependency>
    <groupId>com.alibaba</groupId>
     <artifactId>fastjson</artifactId>
     <version>1.2.38</version>
 </dependency>

 <dependency>
     <groupId>junit</groupId>
     <artifactId>junit</artifactId>
     <version>4.12</version>
     <scope>test</scope>
 </dependency>

 <dependency>
     <groupId>org.elasticsearch.client</groupId>
     <artifactId>elasticsearch-rest-client</artifactId>
     <version>5.6.3</version>
 </dependency>

Core(要存儲的對象)

package top.yuyufeng.learn.lucene.elasticsearch.core;

import java.util.Date;

/**
 * @author yuyufeng
 * @date 2017/12/6
 */
public class BlogCore {
    private String blogId;
    private String blogTitle;
    private String blogContent;
    private Date createTime;
    private String keywords;

    public String getBlogId() {
        return blogId;
    }

    public void setBlogId(String blogId) {
        this.blogId = blogId;
    }

    public String getBlogTitle() {
        return blogTitle;
    }

    public void setBlogTitle(String blogTitle) {
        this.blogTitle = blogTitle;
    }

    public String getBlogContent() {
        return blogContent;
    }

    public void setBlogContent(String blogContent) {
        this.blogContent = blogContent;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public String getKeywords() {
        return keywords;
    }

    public void setKeywords(String keywords) {
        this.keywords = keywords;
    }

    @Override
    public String toString() {
        return "BlogCore{" +
                "blogId='" + blogId + '\'' +
                ", blogTitle='" + blogTitle + '\'' +
                ", blogContent='" + blogContent + '\'' +
                ", createTime=" + createTime +
                ", keywords='" + keywords + '\'' +
                '}';
    }
}

增刪改查

package top.yuyufeng.learn.lucene.elasticsearch;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import top.yuyufeng.learn.lucene.elasticsearch.core.BlogCore;

import java.io.IOException;
import java.util.Collections;
import java.util.Date;

/**
 * @author yuyufeng
 * @date 2017/12/11
 */
public class ClientBasicTest {

    private RestClient restClient;
    private Response response;
    private Header header;

    @Before
    public void testBefore() {
        restClient = RestClient.builder(
                new HttpHost("127.0.0.1", 9200, "http")).build();
        header = new BasicHeader("Content-Type", "application/json");
    }


    /**
     * 增加(更新)索引(帶Id)
     */
    @Test
    public void testIndexWithId() throws IOException {
        BlogCore blog = new BlogCore();
        blog.setBlogId("2");
        blog.setBlogTitle("達(dá)摩院超越業(yè)界龍頭");
        blog.setBlogContent("達(dá)摩院一定也必須要超越英特爾盒发,必須超越微軟例嘱,必須超越IBM,因?yàn)槲覀兩诙皇兰o(jì)宁舰,我們是有機(jī)會后發(fā)優(yōu)勢的拼卵。");
        blog.setCreateTime(new Date());

        String json = JSONObject.toJSONString(blog);
        HttpEntity entity = new StringEntity(json, "utf-8");
        response = restClient.performRequest("PUT", "/test/blog/"+blog.getBlogId(), Collections.emptyMap(), entity, header);
        System.out.println(EntityUtils.toString(response.getEntity()));
    }

    /**
     * 增加索引(ID自動增長)
     */
    @Test
    public void testIndexWithAutoId() throws IOException {
        BlogCore blog = new BlogCore();
        blog.setBlogId("5");
        blog.setBlogTitle("達(dá)摩院成立");
        blog.setBlogContent("達(dá)摩院一定也必須要超越英特爾,必須超越微軟蛮艰,必須超越IBM腋腮,因?yàn)槲覀兩诙皇兰o(jì),我們是有機(jī)會后發(fā)優(yōu)勢的壤蚜。");
        blog.setCreateTime(new Date());

        String json = JSONObject.toJSONString(blog);
        HttpEntity entity = new StringEntity(json, "utf-8");
        response = restClient.performRequest("POST", "/test/blog/", Collections.emptyMap(), entity, header);
        System.out.println(EntityUtils.toString(response.getEntity()));
    }

    /**
     * 刪除
     */
    @Test
    public void testDelete() throws IOException {
        response = restClient.performRequest("DELETE", "/test/blog/2", Collections.emptyMap(), header);
        System.out.println(EntityUtils.toString(response.getEntity()));
    }

    
    @After
    public void testAfter() {
        try {
            restClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

搜索

package top.yuyufeng.learn.lucene.elasticsearch;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import top.yuyufeng.learn.lucene.elasticsearch.core.BlogCore;

import java.io.IOException;
import java.util.Collections;
import java.util.Date;

/**
 * @author yuyufeng
 * @date 2017/12/11
 */
public class ClientSearchTest {

    private RestClient restClient;
    private Response response;
    private Header header;

    @Before
    public void testBefore() {
        restClient = RestClient.builder(
                new HttpHost("127.0.0.1", 9200, "http")).build();
        header = new BasicHeader("Content-Type", "application/json");
    }


    /**
     * 輕量搜索1
     */
    @Test
    public void testSearch1() throws IOException {
        response = restClient.performRequest("GET", "/test/blog/_search?pretty", header);
        System.out.println(EntityUtils.toString(response.getEntity()));
    }

    /**
     * 輕量搜索2
     */
    @Test
    public void testSearch2() throws IOException {
        response = restClient.performRequest("GET", "/test/blog/_search?q=blogTitle:達(dá)摩&pretty", header);
        System.out.println(EntityUtils.toString(response.getEntity()));
    }



    /**
     * 使用查詢表達(dá)式搜索
     */
    @Test
    public void testSearchWithMatch() throws IOException {
        String json = "{" +
                "    \"query\" : {" +
                "        \"match\" : {" +
                "            \"blogTitle\" : \"達(dá)摩阿里巴巴\"" +
                "        }" +
                "    }" +
                "}";
        HttpEntity entity = new StringEntity(json, "utf-8");
        response = restClient.performRequest("GET", "/test/blog/_search?pretty", Collections.emptyMap(),entity, header);
        System.out.println(EntityUtils.toString(response.getEntity()));
    }

    /**
     * 使用查詢表達(dá)式搜索
     */
    @Test
    public void testSearchWithMatchAndFilter() throws IOException {
        String json = "{\n" +
                "    \"query\" : {\n" +
                "        \"bool\": {\n" +
                "            \"must\": {\n" +
                "                \"match\" : {\n" +
                "                    \"blogTitle\" : \"達(dá)摩\" \n" +
                "                }\n" +
                "            },\n" +
                "            \"filter\": {\n" +
                "                \"range\" : {\n" +
                "                    \"blogId\" : { \"gt\" : 1 } \n" +
                "                }\n" +
                "            }\n" +
                "        }\n" +
                "    }\n" +
                "}";
        HttpEntity entity = new StringEntity(json, "utf-8");
        response = restClient.performRequest("GET", "/test/blog/_search?pretty", Collections.emptyMap(),entity, header);
        System.out.println(EntityUtils.toString(response.getEntity()));
    }

    /**
     * 短語搜索  (單詞之間緊挨著)
     * @throws IOException
     */
    @Test
    public void testSearchWithMatchPhrase() throws IOException {
        String json = "{\n" +
                "    \"query\" : {\n" +
                "        \"match_phrase\" : {\n" +
                "            \"blogContent\" : \"阿里巴巴達(dá)摩院\"\n" +
                "        }\n" +
                "    }\n" +
                "}";
        HttpEntity entity = new StringEntity(json, "utf-8");
        response = restClient.performRequest("GET", "/test/blog/_search?pretty", Collections.emptyMap(),entity, header);
        System.out.println(EntityUtils.toString(response.getEntity()));
    }


    /**
     * 高亮
     * @throws IOException
     */
    @Test
    public void testSearchWithighlight() throws IOException {
        String json = "{\n" +
                "    \"query\" : {\n" +
                "        \"match\" : {\n" +
                "            \"blogContent\" : \"阿里巴巴全球研究院\"\n" +
                "        }\n" +
                "    },\n" +
                "    \"highlight\": {\n" +
                "        \"fields\" : {\n" +
                "            \"blogContent\" : {}\n" +
                "        }\n" +
                "    }\n" +
                "}";
        HttpEntity entity = new StringEntity(json, "utf-8");
        response = restClient.performRequest("GET", "/test/blog/_search?pretty", Collections.emptyMap(),entity, header);
        System.out.println(EntityUtils.toString(response.getEntity()));
    }





    @After
    public void testAfter() {
        try {
            restClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

參考文獻(xiàn)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末即寡,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子袜刷,更是在濱河造成了極大的恐慌聪富,老刑警劉巖,帶你破解...
    沈念sama閱讀 212,383評論 6 493
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件水泉,死亡現(xiàn)場離奇詭異善涨,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)草则,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,522評論 3 385
  • 文/潘曉璐 我一進(jìn)店門钢拧,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人炕横,你說我怎么就攤上這事源内。” “怎么了份殿?”我有些...
    開封第一講書人閱讀 157,852評論 0 348
  • 文/不壞的土叔 我叫張陵膜钓,是天一觀的道長。 經(jīng)常有香客問我卿嘲,道長颂斜,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 56,621評論 1 284
  • 正文 為了忘掉前任拾枣,我火速辦了婚禮沃疮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘梅肤。我一直安慰自己司蔬,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,741評論 6 386
  • 文/花漫 我一把揭開白布姨蝴。 她就那樣靜靜地躺著俊啼,像睡著了一般。 火紅的嫁衣襯著肌膚如雪左医。 梳的紋絲不亂的頭發(fā)上授帕,一...
    開封第一講書人閱讀 49,929評論 1 290
  • 那天同木,我揣著相機(jī)與錄音,去河邊找鬼豪墅。 笑死泉手,一個胖子當(dāng)著我的面吹牛黔寇,可吹牛的內(nèi)容都是我干的偶器。 我是一名探鬼主播,決...
    沈念sama閱讀 39,076評論 3 410
  • 文/蒼蘭香墨 我猛地睜開眼缝裤,長吁一口氣:“原來是場噩夢啊……” “哼屏轰!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起憋飞,我...
    開封第一講書人閱讀 37,803評論 0 268
  • 序言:老撾萬榮一對情侶失蹤霎苗,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后榛做,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體唁盏,經(jīng)...
    沈念sama閱讀 44,265評論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,582評論 2 327
  • 正文 我和宋清朗相戀三年检眯,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了厘擂。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,716評論 1 341
  • 序言:一個原本活蹦亂跳的男人離奇死亡锰瘸,死狀恐怖刽严,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情避凝,我是刑警寧澤舞萄,帶...
    沈念sama閱讀 34,395評論 4 333
  • 正文 年R本政府宣布,位于F島的核電站管削,受9級特大地震影響倒脓,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜含思,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 40,039評論 3 316
  • 文/蒙蒙 一崎弃、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧茸俭,春花似錦吊履、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,798評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至腾窝,卻和暖如春缀踪,著一層夾襖步出監(jiān)牢的瞬間居砖,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,027評論 1 266
  • 我被黑心中介騙來泰國打工驴娃, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留奏候,地道東北人。 一個月前我還...
    沈念sama閱讀 46,488評論 2 361
  • 正文 我出身青樓唇敞,卻偏偏與公主長得像蔗草,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子疆柔,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,612評論 2 350

推薦閱讀更多精彩內(nèi)容