es安装与介绍

本文介绍了Elasticsearch的基本概念,如索引、类型、文档和字段,并详细阐述了安装过程,包括Elasticsearch、Kibana和Ik分词器的安装。接着,文章展示了如何使用HTTP API进行索引创建、数据增删改查和查询操作,还提到了Springboot与Elasticsearch的整合。最后,提到了Logstash的引入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

es

 

 

 

概念

Elasticsearch也是基于Lucene的全文检索库,本质也是存储数据,很多概念与MySQL类似的。

对比关系:

索引(indices)--------------------------------Databases 数据库

类型(type)-----------------------------Table 数据表

文档(Document)----------------Row 行

字段(Field)-------------------Columns 列

详细说明:

概念说明
索引库(indices)indices是index的复数,代表许多的索引,
类型(type)类型是模拟mysql中的table概念,一个索引库下可以有不同类型的索引,比如商品索引,订单索引,其数据格式不同。不过这会导致索引库混乱,因此未来版本中会移除这个概念
文档(document)存入索引库原始的数据。比如每一条商品信息,就是一个文档
字段(field)文档中的属性
映射配置(mappings)字段的数据类型、属性、是否索引、是否存储等特性
  • 索引集(Indices,index的复数):逻辑上的完整索引

  • 分片(shard):数据拆分后的各个部分

  • 副本(replica):每个分片的复制

要注意的是:Elasticsearch本身就是分布式的,因此即便你只有一个节点,Elasticsearch默认也会对你的数据进行分片和副本操作,当你向集群添加新数据时,数据也会在新加入的节点中进行平衡。

es安装

  • 安装elastic search

    1. 解压elasticsearch-6.5.4.zip

    2. 打开config/elasticsearch.yml,在文件末尾加上以下配置:(为了让kibanna访问到)

      http.cors.enabled: true
      http.cors.allow-origin: "*"
    3. 启动bin目录中的 elasticsearch.bat

    4. 验证 访问 http://localhost:9200/ ,有如下效果:

      {
        "name" : "Dals5Z1",
        "cluster_name" : "elasticsearch",
        "cluster_uuid" : "ohNc9vzoRua-ItxlDa8aXw",
        "version" : {
          "number" : "6.5.4",
          "build_flavor" : "default",
          "build_type" : "zip",
          "build_hash" : "d2ef93d",
          "build_date" : "2018-12-17T21:17:40.758843Z",
          "build_snapshot" : false,
          "lucene_version" : "7.5.0",
          "minimum_wire_compatibility_version" : "5.6.0",
          "minimum_index_compatibility_version" : "5.0.0"
        },
        "tagline" : "You Know, for Search"
      }
  • 安装kibana

    1. 解压kibana-6.5.4-windows-x86_64.zip

    2. 进入bin,运行kibana.bat

    3. 验证,访问 http://localhost:5601/

    4. 选择左侧的DevTools菜单,即可进入控制台页面

    5. 执行查询条件,即可访问

  • 安装Ik分词器

    1. 解压elasticsearch-analysis-ik-6.5.4.zip

    2. 将文件copy到es的plugins下

    3. 验证

      在控制下输入

      POST _analyze
      {
        "analyzer": "ik_max_word",
        "text":     "我是中国人"
      }

      运行得到结果:

      {
        "tokens" : [
          {
            "token" : "我",
            "start_offset" : 0,
            "end_offset" : 1,
            "type" : "CN_CHAR",
            "position" : 0
          },
          {
            "token" : "是",
            "start_offset" : 1,
            "end_offset" : 2,
            "type" : "CN_CHAR",
            "position" : 1
          },
          {
            "token" : "中国人",
            "start_offset" : 2,
            "end_offset" : 5,
            "type" : "CN_WORD",
            "position" : 2
          },
          {
            "token" : "中国",
            "start_offset" : 2,
            "end_offset" : 4,
            "type" : "CN_WORD",
            "position" : 3
          },
          {
            "token" : "国人",
            "start_offset" : 3,
            "end_offset" : 5,
            "type" : "CN_WORD",
            "position" : 4
          }
        ]
      }
  • 安装拼音分词器

    1. 解压elasticsearch-analysis-pinyin-6.5.4.zip

    2. 将文件copy到es的plugins下

玩一玩es

关于索引

创建索引

语法

Elasticsearch采用Rest风格API,因此其API就是一次http请求,你可以用任何工具发起http请求

创建索引的请求格式:

  • 请求方式:PUT

  • 请求路径:/索引库名(小写)

  • 请求参数:json格式:

    {
        "settings": {
            "number_of_shards": 3,
            "number_of_replicas": 2
          }
    }
    • settings:索引库的设置

      • number_of_shards:分片数量

      • number_of_replicas:副本数量

    测试

    1. postman测试

      路径:http://127.0.0.1:9200/laobai

      请求方式:PUT

      请求体:

      数据格式:json

    2. Kibana测试

      PUT  /laobai2
      {
          "settings": {
              "number_of_shards": 3,
              "number_of_replicas": 2
            }
      }

      结果:

      {
        "acknowledged" : true,
        "shards_acknowledged" : true,
        "index" : "laobai2"
      }

       

查看索引设置

Get请求可以帮我们查看索引信息,格式: GET 索引库名: GET laobai

或者 GET * 查询所有配置

HEAD /索引库名 查看当前索引是否存在:HEAD /laobai

删除索引

Delete请求可以帮我们删除索引信息,格式DELETE /索引库名 : DELETE /laobai

创建映射字段

请求方式依然是PUT

PUT /索引库名/_mapping/类型名称
{
  "properties": {
    "字段名": {
      "type": "类型",
      "index": true,
      "store": true,
      "analyzer": "分词器"
    }
  }
}
  • 类型名称:就是前面将的type的概念,类似于数据库中的不同表 字段名:任意填写 ,可以指定许多属性,例如:

  • type:类型,可以是text、long、short、date、integer、object等

  • index:是否索引,默认为true

  • store:是否存储,默认为false

  • analyzer:分词器,这里的ik_max_word即使用ik分词器

 

查看映射关系

语法:

GET /索引库名/_mapping

示例:

GET /laobai/_mapping

字段属性详解

type

Elasticsearch中支持的数据类型非常丰富:

我们说几个关键的:

  • String类型,又分两种:

    • text:可分词,不可参与聚合

    • keyword:不可分词,数据会作为完整字段进行匹配,可以参与聚合

  • Numerical:数值类型,分两类

    • 基本数据类型:long、interger、short、byte、double、float、half_float

    • 浮点数的高精度类型:scaled_float

      • 需要指定一个精度因子,比如10或100。elasticsearch会把真实值乘以这个因子后存储,取出时再还原。

  • Date:日期类型

    elasticsearch可以对日期格式化为字符串存储,但是建议我们存储为毫秒值,存储为long,节省空间。

index

index影响字段的索引情况。

  • true:字段会被索引,则可以用来进行搜索。默认值就是true

  • false:字段不会被索引,不能用来搜索

index的默认值就是true,也就是说你不进行任何配置,所有字段都会被索引。

但是有些字段是我们不希望被索引的,比如商品的图片信息,就需要手动设置index为false。

store

是否将数据进行额外存储。

在学习lucene和solr时,我们知道如果一个字段的store设置为false,那么在文档列表中就不会有这个字段的值,用户的搜索结果中不会显示出来。

但是在Elasticsearch中,即便store设置为false,也可以搜索到结果。

原因是Elasticsearch在创建文档索引时,会将文档中的原始数据备份,保存到一个叫做_source的属性中。而且我们可以通过过滤_source来选择哪些要显示,哪些不显示。

而如果设置store为true,就会在_source以外额外存储一份数据,多余,因此一般我们都会将store设置为false,事实上,store的默认值就是false。

新增数据

随机生成id

通过POST请求,可以向一个已经存在的索引库中添加数据。

语法:

POST /索引库名/类型名
{
    "key":"value"
}

示例:(前提是你有haoke这个索引库,没有的话,请创建)

POST /haoke/user/
{
    "name":"张三丰",
    "age":20,
    "sex":"男"
}

响应:

{
  "_index" : "haoke",
  "_type" : "user",
  "_id" : "kRgwNnEBjmcmkGbDz3gb",
  "_version" : 1,
  "result" : "created",
  "_shards" : {
    "total" : 2,
    "successful" : 1,
    "failed" : 0
  },
  "_seq_no" : 0,
  "_primary_term" : 1
}

 

通过kibana查看数据:

GET _search
{
    "query":{
        "match_all":{}
    }
}

 

   {
       "_index" : "haoke",
       "_type" : "user",
       "_id" : "kRgwNnEBjmcmkGbDz3gb",
       "_score" : 1.0,
       "_source" : {
           "name" : "张三丰",
           "age" : 20,
           "sex" : "男"
       }
   }
  • _source:源文档信息,所有的数据都在里面。

  • _id:这条文档的唯一标示,与文档自己的id字段没有关联

 

自定义id

如果我们想要自己新增的时候指定id,可以这么做:

POST /索引库名/类型/id值
{
    ...
}

示例:

POST /haoke/user/1
{
    "name":"张无忌",
    "age":20,
    "sex":"男"
}

得到的数据:

{
  "_index" : "haoke",
  "_type" : "user",
  "_id" : "1",
  "_version" : 1,
  "result" : "created",
  "_shards" : {
    "total" : 2,
    "successful" : 1,
    "failed" : 0
  },
  "_seq_no" : 0,
  "_primary_term" : 1
}

 

智能判断

在学习Solr时我们发现,我们在新增数据时,只能使用提前配置好映射属性的字段,否则就会报错。

不过在Elasticsearch中并没有这样的规定。

事实上Elasticsearch非常智能,你不需要给索引库设置任何mapping映射,它也可以根据你输入的数据来判断类型,动态添加数据映射。

在看下索引库的映射关系: GET /haoke/_mapping

{
  "haoke" : {
    "mappings" : {
      "user" : {
        "properties" : {
          "age" : {
            "type" : "long"
          },
          "name" : {
            "type" : "text",
            "fields" : {
              "keyword" : {
                "type" : "keyword",
                "ignore_above" : 256
              }
            }
          },
          "sex" : {
            "type" : "text",
            "fields" : {
              "keyword" : {
                "type" : "keyword",
                "ignore_above" : 256
              }
            }
          }
        }
      }
    }
  }
}

 

修改数据

把刚才新增的请求方式改为PUT,就是修改了。不过修改必须指定id,

  • id对应文档存在,则修改

  • id对应文档不存在,则新增

比如,我们把id为3的数据进行修改:

PUT /haoke/user/3
{
    "name":"殷素素",
    "age":38,
    "sex":"女"
}

删除数据

删除使用DELETE请求,同样,需要根据id进行删除:

语法: DELETE /索引库名/类型名/id值 : DELETE /haoke/user/kRgwNnEBjmcmkGbDz3gb

查询数据

我们从4块来讲查询:

  • 基本查询

  • _source过滤

  • 结果过滤

  • 高级查询

  • 排序

 

基本查询:

基本语法

GET /索引库名/_search
{
    "query":{
        "查询类型":{
            "查询条件":"查询条件值"
        }
    }
}

这里的query代表一个查询对象,里面可以有不同的查询属性

  • 查询类型:

    • 例如:match_all, matchterm , range 等等

  • 查询条件:查询条件会根据类型的不同,写法也有差异,后面详细讲解

 

查询所有(match_all)

示例:

GET /haoke/_search
{
    "query":{
        "match_all": {}
    }
}
  • query:代表查询对象

  • match_all:代表查询所有

结果:

{
  "took" : 0,
  "timed_out" : false,
  "_shards" : {
    "total" : 15,
    "successful" : 15,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : 5,
    "max_score" : 1.0,
    "hits" : [
      {
        "_index" : ".kibana_1",
        "_type" : "doc",
        "_id" : "space:default",
        "_score" : 1.0,
        "_source" : {
          "space" : {
            "name" : "Default",
            "description" : "This is your default space!",
            "color" : "#00bfb3",
            "_reserved" : true
          },
          "type" : "space",
          "updated_at" : "2020-04-01T13:49:39.765Z"
        }
      },
      {
        "_index" : ".kibana_1",
        "_type" : "doc",
        "_id" : "config:6.5.4",
        "_score" : 1.0,
        "_source" : {
          "config" : {
            "buildNum" : 18878
          },
          "type" : "config",
          "updated_at" : "2020-04-01T13:50:30.920Z"
        }
      },
      {
        "_index" : ".kibana_1",
        "_type" : "doc",
        "_id" : "telemetry:telemetry",
        "_score" : 1.0,
        "_source" : {
          "telemetry" : {
            "enabled" : false
          },
          "type" : "telemetry",
          "updated_at" : "2020-04-01T13:59:35.586Z"
        }
      },
      {
        "_index" : "haoke",
        "_type" : "user",
        "_id" : "1",
        "_score" : 1.0,
        "_source" : {
          "name" : "张无忌",
          "age" : 20,
          "sex" : "男"
        }
      },
      {
        "_index" : "haoke",
        "_type" : "user",
        "_id" : "3",
        "_score" : 1.0,
        "_source" : {
          "name" : "殷素素",
          "age" : 38,
          "sex" : "女"
        }
      }
    ]
  }
}
  • took:查询花费时间,单位是毫秒

  • time_out:是否超时

  • _shards:分片信息

  • hits:搜索结果总览对象

    • total:搜索到的总条数

    • max_score:所有结果中文档得分的最高分

    • hits:搜索结果的文档对象数组,每个元素是一条搜索到的文档信息

      • _index:索引库

      • _type:文档类型

      • _id:文档id

      • _score:文档得分

      • _source:文档的源数据

 

匹配查询(match)

我们先加入一条数据,便于测试:

POST /haoke/user/4
{
    "name":"张三丰",
    "age":150,
    "sex":"男"
}
  • or关系

match类型查询,会把查询条件进行分词,然后进行查询,多个词条之间是or的关系

GET /haoke/_search
{
    "query":{
        "match":{
            "name":"张无忌"
        }
    }
}

在上面的案例中,不仅会查询到张无忌,而且姓张的都会查询到,多个词之间是or的关系。

 

  • and关系

某些情况下,我们需要更精确查找,我们希望这个关系变成and,可以这样做:

GET /haoke/_search
{
    "query":{
        "match": {
          "name": {
            "query": "张无忌",
            "operator": "and"
          }
        }
    }
}

本例中,只有同时包含无忌的词条才会被搜索到。

 

  • or和and之间?

orand 间二选一有点过于非黑即白。 如果用户给定的条件分词后有 5 个查询词项,想查找只包含其中 4 个词的文档,该如何处理?将 operator 操作符参数设置成 and 只会将此文档排除。

有时候这正是我们期望的,但在全文搜索的大多数应用场景下,我们既想包含那些可能相关的文档,同时又排除那些不太相关的。换句话说,我们想要处于中间某种结果。

match 查询支持 minimum_should_match 最小匹配参数, 这让我们可以指定必须匹配的词项数用来表示一个文档是否相关。我们可以将其设置为某个具体数字,更常用的做法是将其设置为一个百分数,因为我们无法控制用户搜索时输入的单词数量:

GET /haoke/_search
{
    "query":{
        "match":{
            "name":{
            	"query":"张无忌",
            	"minimum_should_match": "55%"
            }
        }
    }
}

多字段查询(multi_match)

multi_matchmatch类似,不同的是它可以在多个字段中查询

GET /haoke/_search
{
    "query":{
        "multi_match": {
            "query":    "张男",
            "fields":   [ "name", "sex" ]
        }
	}
}

本例中,我们会在name字段和sex字段中查询

 

词条匹配(term)

term 查询被用于精确值 匹配,这些精确值可能是数字、时间、布尔或者那些未分词的字符串

GET /haoke/_search
{
    "query":{
        "term":{
            "age":38
        }
    }
}

多词条精确匹配(terms)

terms 查询和 term 查询一样,但它允许你指定多值进行匹配。如果这个字段包含了指定值中的任何一个值,那么这个文档满足条件:

GET /haoke/_search
{
    "query":{
        "terms":{
            "age":[38,50]
        }
    }
}

高亮

POST /haoke/user/_search
{ 
  "query" : { 
    "match" : {  
        "name" : "张无忌素素" 
    } 
  },
  "highlight": { "fields": { "name": {} } }
}

 

结果过滤

默认情况下,elasticsearch在搜索的结果中,会把文档中保存在_source的所有字段都返回。

如果我们只想获取其中的部分字段,我们可以添加_source的过滤

直接指定字段

示例:

GET /haoke/_search
{
  "_source": ["name","age"],
  "query": {
    "term": {
      "age": 38
    }
  }
}

指定includes和excludes

我们也可以通过:

  • includes:来指定想要显示的字段

  • excludes:来指定不想要显示的字段

二者都是可选的。

示例:

GET /haoke/_search
{
  "_source": {
    "includes":["name","age"]
  },
  "query": {
    "term": {
      "age": 38
    }
  }
}

与下面的结果将是一样的:

GET /haoke/_search
{
  "_source": {
     "excludes": ["sex"]
  },
  "query": {
    "term": {
      "age": 38
    }
  }
}

 

高级查询

布尔组合(bool)

bool把各种其它查询通过must(与)、must_not(非)、should(或)的方式进行组合

GET /haoke/_search
{
    "query":{
        "bool":{
        	"must":     { "match": { "name": "张" }},
        	"must_not": { "match": { "name":  "翠山" }},
        	"should":   { "match": { "name": "三丰" }}
        }
    }
}

 

范围查询(range)

range 查询找出那些落在指定区间内的数字或者时间

GET /haoke/_search
{
    "query":{
        "range": {
            "age": {
                "gte":  50,
                "lt":   160
            }
    	}
    }
}

range查询允许以下字符:

操作符说明
gt大于
gte大于等于
lt小于
lte小于等于

 

模糊查询(fuzzy)

我们新增一个商品:

POST /haoke/user/8
{
    "name":"Angular Baby",
    "age":20,
    "sex":"女"
}

 

fuzzy 查询是 term 查询的模糊等价。它允许用户搜索词条与实际词条的拼写出现偏差,但是偏差的编辑距离不得超过2:

GET /haoke/_search
{
  "query": {
    "fuzzy": {
      "name": "Angulbr"
    }
  }
}

 

过滤(filter)

条件查询中进行过滤

所有的查询都会影响到文档的评分及排名。如果我们需要在查询结果中进行过滤,并且不希望过滤条件影响评分,那么就不要把过滤条件作为查询条件来用。而是使用filter方式:

GET /haoke/_search
{
    "query":{
        "bool":{
        	"must":{ "match": { "name": "张" }},
        	"filter":{
                "range":{"age":{"gt":60,"lt":160}}
        	}
        }
    }
}

注意:filter中还可以再次进行bool组合条件过滤。

 

无查询条件,直接过滤

如果一次查询只有过滤,没有查询条件,不希望进行评分,我们可以使用constant_score取代只有 filter 语句的 bool 查询。在性能上是完全相同的,但对于提高查询简洁性和清晰度有很大帮助。

GET /haoke/_search
{
    "query":{
        "constant_score":   {
            "filter": {
            	 "range":{"age":{"gt":50,"lt":170}}
            }
        }
}

 

排序

sort 可以让我们按照不同的字段进行排序,并且通过order指定排序的方式

GET /haoke/_search
{
  "query": {
    "match": {
      "name": "张无忌"
    }
  },
  "sort": [
    {
      "age": {
        "order": "desc"
      }
    }
  ]
}

聚合aggregations

聚合可以让我们极其方便的实现对数据的统计、分析。例如:

为了测试聚合,我们先批量导入一些数据

创建索引:

PUT /cars
{
  "settings": {
    "number_of_shards": 1,
    "number_of_replicas": 0
  },
  "mappings": {
    "transactions": {
      "properties": {
        "color": {
          "type": "keyword"
        },
        "make": {
          "type": "keyword"
        }
      }
    }
  }
}

注意:在ES中,需要进行聚合、排序、过滤的字段其处理方式比较特殊,因此不能被分词。这里我们将color和make这两个文字类型的字段设置为keyword类型,这个类型不会被分词,将来就可以参与聚合

 

导入数据

POST /cars/transactions/_bulk
{ "index": {}}
{ "price" : 10000, "color" : "red", "make" : "honda", "sold" : "2014-10-28" }
{ "index": {}}
{ "price" : 20000, "color" : "red", "make" : "honda", "sold" : "2014-11-05" }
{ "index": {}}
{ "price" : 30000, "color" : "green", "make" : "ford", "sold" : "2014-05-18" }
{ "index": {}}
{ "price" : 15000, "color" : "blue", "make" : "toyota", "sold" : "2014-07-02" }
{ "index": {}}
{ "price" : 12000, "color" : "green", "make" : "toyota", "sold" : "2014-08-19" }
{ "index": {}}
{ "price" : 20000, "color" : "red", "make" : "honda", "sold" : "2014-11-05" }
{ "index": {}}
{ "price" : 80000, "color" : "red", "make" : "bmw", "sold" : "2014-01-01" }
{ "index": {}}
{ "price" : 25000, "color" : "blue", "make" : "ford", "sold" : "2014-02-12" }

首先,我们按照 汽车的颜色color来划分

GET /cars/_search
{
    "size" : 0,
    "aggs" : { 
        "popular_colors" : { 
            "terms" : { 
              "field" : "color"
            }
        }
    }
}
  • size: 查询条数,这里设置为0,因为我们不关心搜索到的数据,只关心聚合结果,提高效率

  • aggs:声明这是一个聚合查询,是aggregations的缩写

    • popular_colors:给这次聚合起一个名字,任意。

      • terms:划分桶的方式,这里是根据词条划分

        • field:划分桶的字段

结果:

{
  "took": 1,
  "timed_out": false,
  "_shards": {
    "total": 1,
    "successful": 1,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": 8,
    "max_score": 0,
    "hits": []
  },
  "aggregations": {
    "popular_colors": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": "red",
          "doc_count": 4
        },
        {
          "key": "blue",
          "doc_count": 2
        },
        {
          "key": "green",
          "doc_count": 2
        }
      ]
    }
  }
}
  • hits:查询结果为空,因为我们设置了size为0

  • aggregations:聚合的结果

  • popular_colors:我们定义的聚合名称

  • buckets:查找到的桶,每个不同的color字段值都会形成一个桶

    • key:这个桶对应的color字段的值

    • doc_count:这个桶中的文档数量

通过聚合的结果我们发现,目前红色的小车比较畅销!

Springboot-Es整合走起来

依赖:

<!--引入父工程-->
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.6.RELEASE</version>
</parent>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

配置:

#集群名
spring.data.elasticsearch.cluster-name=elasticsearch
#默认 9300 是 Java 客户端的端口。9200 是支持 Restful HTTP 的接口
spring.data.elasticsearch.cluster-nodes = 127.0.0.1:9300

搞事情:

前夜

import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
@Document(indexName = "goods",type = "item" ,shards = 1)
public class Item {
    @Id
    private Long id;
    private String title; //标题
    private String category;// 分类
    private String brand; // 品牌
    private Double price; // 价格
    private String images; // 图片地址

    public Item() {
    }

    public Item(Long id, String title, String category, String brand, Double price, String images) {
        this.id = id;
        this.title = title;
        this.category = category;
        this.brand = brand;
        this.price = price;
        this.images = images;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    public String getImages() {
        return images;
    }

    public void setImages(String images) {
        this.images = images;
    }
}

 

创建索引库:

@SpringBootTest
@RunWith(SpringRunner.class)
public class TestEs {
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;
    @Test
    public void createIndex(){
        //通过模板创建索引
        elasticsearchTemplate.createIndex(Item.class);
    }
}

数据的增删改查

前夜

import org.laobai.demo.es.entity.Item;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

public interface ItemRepository extends ElasticsearchRepository<Item,Long> {
}

增删改查

@SpringBootTest
@RunWith(SpringRunner.class)
public class TestEs {
    @Autowired
    private ItemRepository itemRepository;

    //添加数据
    @Test
    public void testInsert() {
        Item item = new Item(1L, "小米手机7", " 手机",
                "小米", 3499.00, "http://jiusan.org/13123.jpg");
        itemRepository.save(item);
    }

    //批量增加
    @Test
    public void testBatch() {
        List<Item> list = new ArrayList<>();
        list.add(new Item(2L, "坚果手机R1", " 手机", "锤子", 3699.00, "http://jiusan.org/123.jpg"));
        list.add(new Item(3L, "华为META10", " 手机", "华为", 4499.00, "http://jiusan.org/3.jpg"));
        list.add(new Item(4L, "小米Mix2S", "手机", "小米", 4299.00, "http://jiusan.org/13123.jpg"));
        list.add(new Item(5L, "荣耀V10", "手机", "华为", 2799.00, "http://jiusan.org/13123.jpg"));
        // 接收对象集合,实现批量新增
        itemRepository.saveAll(list);
    }

    public void testUpdate() {
        //抱歉没有代码,这个呀,跟咱们的新增是一个方法
    }
    //删除
    @Test
    public void testDel(){
        itemRepository.deleteById(1L);
    }
    // 基础查询
    @Test
    public void testBaseQuery(){
        Iterable<Item> price = itemRepository.findAll(Sort.by(Sort.Direction.DESC, "price"));
        price.forEach(item-> System.out.println(item));
    }
     // 根据name搜索
    @Test
    public void testBaseQuery2(){
        MatchQueryBuilder queryBuilder = QueryBuilders.matchQuery("title", "小米");
        Iterable<Item> iterable = itemRepository.search(queryBuilder);
        iterable.forEach(item-> System.out.println(item));
    }
    // 分页
    @Test
    public void testBaseQuery3(){
        MatchQueryBuilder queryBuilder = QueryBuilders.matchQuery("title", "小米");
        // 从0开始
        Pageable page = PageRequest.of(0,1);
        Iterable<Item> iterable = itemRepository.search(queryBuilder,page);
        iterable.forEach(item-> System.out.println(item));
    }
    //自定义查询
    @Test
    public void testBaseQuery4(){
        List<Item> list = itemRepository.findByPriceBetween(3000.00, 4300.00);
        list.forEach(item-> System.out.println(item));
    }

 

Spring Data 的另一个强大功能,是根据方法名称自动实现功能。

比如:你的方法名叫做:findByTitle,那么它就知道你是根据title查询,然后自动帮你完成,无需写实现类。

当然,方法名称要符合一定的约定:

KeywordSampleElasticsearch Query String
AndfindByNameAndPrice{"bool" : {"must" : [ {"field" : {"name" : "?"}}, {"field" : {"price" : "?"}} ]}}
OrfindByNameOrPrice{"bool" : {"should" : [ {"field" : {"name" : "?"}}, {"field" : {"price" : "?"}} ]}}
IsfindByName{"bool" : {"must" : {"field" : {"name" : "?"}}}}
NotfindByNameNot{"bool" : {"must_not" : {"field" : {"name" : "?"}}}}
BetweenfindByPriceBetween{"bool" : {"must" : {"range" : {"price" : {"from" : ?,"to" : ?,"include_lower" : true,"include_upper" : true}}}}}
LessThanEqualfindByPriceLessThan{"bool" : {"must" : {"range" : {"price" : {"from" : null,"to" : ?,"include_lower" : true,"include_upper" : true}}}}}
GreaterThanEqualfindByPriceGreaterThan{"bool" : {"must" : {"range" : {"price" : {"from" : ?,"to" : null,"include_lower" : true,"include_upper" : true}}}}}
BeforefindByPriceBefore{"bool" : {"must" : {"range" : {"price" : {"from" : null,"to" : ?,"include_lower" : true,"include_upper" : true}}}}}
AfterfindByPriceAfter{"bool" : {"must" : {"range" : {"price" : {"from" : ?,"to" : null,"include_lower" : true,"include_upper" : true}}}}}
LikefindByNameLike{"bool" : {"must" : {"field" : {"name" : {"query" : "?*","analyze_wildcard" : true}}}}}
StartingWithfindByNameStartingWith{"bool" : {"must" : {"field" : {"name" : {"query" : "?*","analyze_wildcard" : true}}}}}
EndingWithfindByNameEndingWith{"bool" : {"must" : {"field" : {"name" : {"query" : "*?","analyze_wildcard" : true}}}}}
Contains/ContainingfindByNameContaining{"bool" : {"must" : {"field" : {"name" : {"query" : "**?**","analyze_wildcard" : true}}}}}
InfindByNameIn(Collection<String>names){"bool" : {"must" : {"bool" : {"should" : [ {"field" : {"name" : "?"}}, {"field" : {"name" : "?"}} ]}}}}
NotInfindByNameNotIn(Collection<String>names){"bool" : {"must_not" : {"bool" : {"should" : {"field" : {"name" : "?"}}}}}}
NearfindByStoreNearNot Supported Yet !
TruefindByAvailableTrue{"bool" : {"must" : {"field" : {"available" : true}}}}
FalsefindByAvailableFalse{"bool" : {"must" : {"field" : {"available" : false}}}}
OrderByfindByAvailableTrueOrderByNameDesc{"sort" : [{ "name" : {"order" : "desc"} }],"bool" : {"must" : {"field" : {"available" : true}}}}

例如,我们来按照价格区间查询,定义这样的一个方法:

public interface ItemRepository extends ElasticsearchRepository<Item,Long> {

    /**
     * 根据价格区间查询
     * @param price1
     * @param price2
     * @return
     */
    List<Item> findByPriceBetween(double price1, double price2);
}

 

 

Logstash

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值