搜索学习--Elasticsearch全文搜索服务器的基本使用

前言

之前我们使用Solr全文搜索服务器来建立我们自己的搜索,本篇文章将介绍跟Solr类似的另一种搜索服务器——Elasticsearch。就个人而言,Elasticsearch比Solr使用更方便,只要使用Http通过Json传输就可以去使用了。对于ElasticSearch服务器的部署,分布式,集群这里就先不介绍了。部署启动后,访问 http://127.0.0.1:9200/,显示如下类似信息,说明服务器已经起来了。
> {
"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"
}
接下来就是通过客户端去调用了,这里使用Java

依赖

 
    com.alibaba
     fastjson
     1.2.38
 

 
     junit
     junit
     4.12
     test
 

 
     org.elasticsearch.client
     elasticsearch-rest-client
     5.6.3
 

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("达摩院超越业界龙头");
        blog.setBlogContent("达摩院一定也必须要超越英特尔,必须超越微软,必须超越IBM,因为我们生于二十一世纪,我们是有机会后发优势的。");
        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("达摩院成立");
        blog.setBlogContent("达摩院一定也必须要超越英特尔,必须超越微软,必须超越IBM,因为我们生于二十一世纪,我们是有机会后发优势的。");
        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:达摩&pretty", header);
        System.out.println(EntityUtils.toString(response.getEntity()));
    }



    /**
     * 使用查询表达式搜索
     */
    @Test
    public void testSearchWithMatch() throws IOException {
        String json = "{" +
                "    \"query\" : {" +
                "        \"match\" : {" +
                "            \"blogTitle\" : \"达摩阿里巴巴\"" +
                "        }" +
                "    }" +
                "}";
        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()));
    }

    /**
     * 使用查询表达式搜索
     */
    @Test
    public void testSearchWithMatchAndFilter() throws IOException {
        String json = "{\n" +
                "    \"query\" : {\n" +
                "        \"bool\": {\n" +
                "            \"must\": {\n" +
                "                \"match\" : {\n" +
                "                    \"blogTitle\" : \"达摩\" \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\" : \"阿里巴巴达摩院\"\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();
        }
    }
}

参考文献

  • https://www.elastic.co/guide/cn/elasticsearch/guide/current/index.html

你可能感兴趣的:(搜索学习--Elasticsearch全文搜索服务器的基本使用)