栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

ElasticSearch(弹性搜索)原理与用法概述

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

ElasticSearch(弹性搜索)原理与用法概述

一.Elasticsearch介绍

ElasticSearch是一个开源的高扩展的分布式全文检索引擎,它也是使用Java开发并使用Lucene作为其核心来实现所有索引和搜索的功能,但是它的目的是通过简单的RESTful API来隐藏Lucene的复杂性,从而让全文搜索变得简单。

作者说:“Elasticsearch is schemaless. It can eat anything you feed it and process it for later querying. “

优点:

  1. 近乎实时的存储、检索数据;

  2. 本身扩展性很好,可以扩展到上百台服务器,处理PB级别的数据。

主要解决的问题:

  1. 检索相关数据; 

  2. 返回统计结果; 

  3. 速度快


二.Elasticsearch的核心概念1.Cluster:集群。

ES可以部署在独立的单个搜索服务器。为了处理大型数据集,实现容错和高可用性,ES可以运行在许多互相合作的服务器上,成为一个集群。

2.Node:节点。

形成集群的每个服务器即是节点。

3.Shard:分片。

当有大量的文档时,由于内存的限制、磁盘处理能力不足、无法足够快的响应客户端的请求等,一个节点可能不够。这种情况下,数据可以分为较小的分片。每个分片放到不同的服务器上,分片再组合这个过程用户是感知不到的。 

4.Replia:副本。

为提高查询吞吐量或实现高可用性,可以使用分片副本。 
副本是一个分片的精确复制,每个分片可以有零个或多个副本。ES中可以有许多相同的分片,其中之一被选择更改索引操作,这种特殊的分片称为主分片。 
当主分片丢失时,该分片所在的数据不可用时,集群将副本提升为新的主分片。

5.全文检索。

全文检索就是对一篇文章进行索引,可以根据关键字搜索,类似于mysql里的like语句。 
全文索引就是把内容根据词的意义进行分词,然后分别创建索引。

为清楚区分关系型数据库和ES的概念,罗列一个表格:

关系型数据库



ES


Database

数据库


Index

索引

Table

表


Type

类型

Row

行


document

文档

Column

列


Field

字段

Schema

图表


Mapping

映射

Index

索引


Everything   is indexed

所有内容都已编入索引

SQL

SQL语句


Query DSL

DSL命令行

SELECt * FROM….

查询语句


GET   http://....

查询语句

UPDATE table   SET…

修改语句


PUT/POST http://....

修改语句

1.关系型数据库中的数据库(Database),等价于ES中的索引(Index) 
2.一个数据库下面有N张表(Table),等价于1个索引Index下面有N多类型(Type), 
3.一个数据库表(Table)下的数据由多行(ROW)多列(column,属性)组成,等价于1个Type由多个文档(document)和多Field组成。 
4.在一个关系型数据库里面,schema定义了表、每个表的字段,还有表和字段之间的关系。 与之对应的,在ES中:Mapping定义索引下的Type的字段处理规则,即索引如何建立、索引类型、是否保存原始索引JSON文档、是否压缩原始JSON文档、是否需要分词处理、如何进行分词处理等。 
5.在数据库中的增insert、删delete、改update、查search操作等价于ES中的增PUT/POST、删Delete、改_update、查GET.

它们相似又有区别,需要区分开。

三.Elasticsearch的CRUD操作

关键字:

GET:获取请求对象的当前状态。 
POST:改变对象的当前状态。 
PUT:创建一个对象。 
DELETE:销毁对象。 
HEAD:请求获取对象的基础信息。

一.新建(对应insert)

http://localhost:8899/imooc/ariticle/1 put
{
    "title":"New version of Elasticsearch released!",
    "content":"Version 1.0 released today!",
    "tags":["announce","elasticsearch","release"]
}

新建成功:

{
-  "_index": "imooc",
-  "_type": "ariticle",
-  "_id": "1 -d",
-  "_version": 1,
-  "_shards": {
    - "total": 2,
    - "successful": 1,
    - "failed": 0
- },
-  "created": true
}

二.查找(对应select)

curl -XGET http://localhost:8899/imooc/ariticle/1

查找成功结果为

{
-  "_index": "imooc",
-  "_type": "ariticle",
-  "_id": "1",
-  "_version": 1,
-  "found": true,
-  "_source": {
    - "title": "New version of Elasticsearch released!",
    - "content": "Version 1.0 released today!",
    - "tags": [
      - "announce"
      - ,
      - "elasticsearch"
      - ,
      - "release"
   - ]
-  }
}

如果查找失败

{
    - "_index": "imooc",
    - "_type": "ariticle",
    - "_id": "11",
    - "found": false
}

根据关键字检索:

  1. 查询cotent列包含版本为1.0的信息

http://localhost:8899/imooc/_search?pretty&q=content:1.0

  2.查询title中包含“enhance”字段的数据信息

curl -XGET http://localhost:8899/imooc/ariticle/_search?pretty -d `
>{"query":{
>  "term":
>      {"title":"enhance"}
>    }
>}'

  3.查询ID值为3,5,7的数据信息

curl‑XGET http://localhost:8899/imooc/ariticle/_search?pretty -d `
>{ "query" : {"terms" :
>       {"_id" : [ "3", "5", "7" ] }
>    }
>}'

三.更新修改(对应update)

curl ‑XPUT "http://localhost:8989/imooc/ariticle/1" ‑d '
{"script":"ctx._source.content = "new version 2.0 20160714""}

查询更新后结果

{
-  "_index": "blog",
-  "_type": "ariticle",
-  "_id": "1",
-  "_version": 2,
-  "found": true,
-  "_source": {
    - "title": "New version of Elasticsearch released!",
    - "content": "new version 2.0 20160714",
    - "tags": [
      - "announce"
      - ,
      - "elasticsearch"
      - ,
      - "release"
   - ]
-  }
}

四.删除(对应delete)

curl‑XDELETE http://localhost:8899/imooc/ariticle/1

以上便是ES的CRUD操作,需要动手操作熟悉一波。

四.Elasticsearch语句在Java中的应用

前面讲了这么多基础性的知识,下面来看看在Java代码如何和使用功能强大的ES。

Elasticsearch的Java客户端功能强大; 它可以启动嵌入式实例并在必要时运行管理任务。但在这里,我专注于针对您已经运行的节点运行应用程序任务。

使用Elasticsearch运行Java应用程序时,可以使用两种操作模式。应用程序可以在Elasticsearch集群中采用更主动或更被动的角色。在更活跃的情况下,称为节点客户端,应用程序实例接收来自集群的请求,并确定哪个节点应该像正常节点那样处理请求。(应用程序甚至可以托管索引并提供请求。)另一种模式(称为传输客户端)只是将任何请求转发到另一个Elasticsearch节点,该节点确定最终目标。

获取传输客户端
Client client = TransportClient.builder().build()
   .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));

如果要连接到Elasticsearch集群,则构建器可以接受多个地址。(在这种情况下,您只有一个localhost节点。)连接到端口9300,而不是像cURL那样连接到CS200用于REST API。Java客户端使用此特殊端口,使用9200将无法正常工作。(其他Elasticsearch客户端 - 一个Python客户端 - 使用9200来访问REST API。)

在服务器启动时创建客户端,并在整个请求处理过程中使用它。Spark使用Mustache模板引擎的Java实现呈现页面。

1.基本搜索


Spark.get("/", (request, response)‑>{
  SearchResponse searchResponse = client.prepareSearch("music").setTypes("lyrics").execute().actionGet();
  SearchHit[] hits = searchResponse.getHits().getHits();
  Map attributes = new HashMap<>();
  attributes.put("songs", hits);
  return new ModelAndView(attributes, "index.mustache");
  }, new MustacheTemplateEngine());

2.高级查询和匹配突出显示

Spark.get("/search", (request, response) ‑> {
   SearchRequestBuilder srb = client.prepareSearch("music").setTypes("lyrics");
   String lyricParam = request.queryParams("query");
   QueryBuilder lyricQuery = null;
   if(lyricParam != null && lyricParam.trim().length() > 0){
     lyricQuery = QueryBuilders.matchQuery("lyrics", lyricParam);
   }
   String artistParam = request.queryParams("artist");
   QueryBuilder artistQuery = null;
   if(artistParam != null && artistParam.trim().length() > 0){
     artistQuery = QueryBuilders.matchQuery("artist", artistParam);
   }
   if(lyricQuery != null && artistQuery == null){
     srb.setQuery(lyricQuery).addHighlightedField("lyrics", 0, 0);
   }else if(lyricQuery == null && artistQuery != null){
     srb.setQuery(artistQuery);
   }else if(lyricQuery != null && artistQuery != null){
     srb.setQuery(QueryBuilders.andQuery(artistQuery, 
       lyricQuery)).addHighlightedField("lyrics", 0, 0);
     }
     SearchResponse searchResponse = srb.execute().actionGet();SearchHit[] hits = searchResponse.getHits().getHits();
   Map attributes = new HashMap<>();
   attributes.put("songs", hits);
   return new ModelAndView(attributes, "index.mustache");}, new MustacheTemplateEngine());
三.插入索引
Spark.post("/save", (request, response) ‑> {
   StringBuilder json = new StringBuilder("{");
   json.append(""name":""+request.raw().getParameter("name")+"",");
   json.append(""artist":""+request.raw().getParameter("artist")+"",");
   json.append(""year":"+request.raw().getParameter("year")+",");
   json.append(""album":""+request.raw().getParameter("album")+"",");
   json.append(""lyrics":""+request.raw().getParameter("lyrics")+""}");
   IndexRequest indexRequest = new IndexRequest("music", "lyrics",
       UUID.randomUUID().toString());
   indexRequest.source(json.toString());
   IndexResponse esResponse = client.index(indexRequest).actionGet();
   Map attributes = new HashMap<>();
   return new ModelAndView(attributes, "index.mustache");
   }, new MustacheTemplateEngine());

在这里,您可以通过直接生成JSON字符串来创建它StringBuilder。在生产应用程序中,使用像Boon或Jackson这样的库。

执行Elasticsearch工作的部分是:

IndexRequest indexRequest = new IndexRequest("music", "lyrics", UUID.randomUUID().toString());

在这种情况下,使用UUID生成ID。

关于ElasticSearch(弹性搜索)的原理与用法的内容就是这些,希望对大家有所帮助~~


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/238816.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号