美文网首页
一文弄懂 ElasticSearch 使用

一文弄懂 ElasticSearch 使用

作者: 左诗右码 | 来源:发表于2024-02-19 13:34 被阅读0次

ElasticSearch 和 mysql 数据库的概念对比

MySQL Elasticsearch
数据库(Databases) 索引(Index)(每个 Index (即数据库)的名字必须是小写)
表(Table) 类型 (Type)(其中,一个 index 可以定义多个 type,但一般习惯仅配置一个 type,7.x 版本后的 es 删除了 type 的概念,且默认的 Type 为 _doc
表结构定义(Schema) mapping (mapping 定义了 index 中的 type,mapping 可以显示的定义,也可以在 document 被索引时自动生成)
记录(Row) 文档(Document)
字段(Column) 字段(Fields)

ElasticSearch 的简单使用

其他

# 获取所有数据
curl -X GET "http://localhost:9200/*"

# 删除所有数据
curl -X DELETE "http://localhost:9200/*"

# 测试分词
curl -X GET "http://localhost:9200/_analyze" -H 'Content-Type: application/json' -d '{  "analyzer": "ik_max_word",  "text": "hello 我是人见人爱的 alex"}'

查看当前节点的所有 index

curl -X GET 'http://localhost:9200/_cat/indices?v'

列出所有 index 所包含的 Type

Document 可以分组,比如 weather 这个 Index 里面,可以按城市分组(北京和上海),也可以按气候分组(晴天和雨天)。这种分组就叫做 Type,它是虚拟的逻辑分组,用来过滤 Document
7.x默认的 Type 为 _doc

curl 'localhost:9200/_mapping?pretty=true'

新建索引 index (创建表)


# 新建一个名叫 `test_index` 的 Index
curl -X PUT http://localhost:9200/test_index  

# 在 Elasticsearch 的返回中如果包含了 "acknowledged" : true, 则代表请求成功。
{"acknowledged":true,"shards_acknowledged":true,"index":"test_index"}

删除索引 index


# 删除名叫 `test_index` 的 Index
curl -X DELETE http://localhost:9200/test_index

查看索引 index


curl http://localhost:9200/test_index

{"test_index":{"aliases":{},"mappings":{},"settings":{"index":{"creation_date":"1617069458624","number_of_shards":"1","number_of_replicas":"1","uuid":"XKjqatZTSOu9I_PiwzaNOQ","version":{"created":"7090199"},"provided_name":"test_index"}}}}

# 可以加上 pretty 参数,返回比较人性化的结构
curl http://localhost:9200/test_index\?pretty                                                                           
{
  "test_index" : {
    "aliases" : { },
    "mappings" : { },
    "settings" : {
      "index" : {
        "creation_date" : "1617069458624",
        "number_of_shards" : "1",
        "number_of_replicas" : "1",
        "uuid" : "XKjqatZTSOu9I_PiwzaNOQ",
        "version" : {
          "created" : "7090199"
        },
        "provided_name" : "test_index"
      }
    }
  }
}

创建类型 Type

对应的接口地址是 /{index_name}/_mapping


curl -H 'Content-Type: application/json' -X PUT http://localhost:9200/test_index/_mapping?pretty -d 
'{
  "properties": {
    "title": { "type": "text", "analyzer": "ik_smart" }, 
    "description": { "type": "text", "analyzer": "ik_smart" },
    "price": { "type": "scaled_float", "scaling_factor": 100 }
  }
}'

# 会返回

{
  "acknowledged" : true
}


curl -H 'Content-Type: application/json' -X PUT http://localhost:9200/products/_mapping/?pretty -d'{
  "properties": {
    "brand_id": { "type": "integer" },
    "type": { "type": "integer" },
    "title": { "type": "text", "analyzer": "ik_smart" }, 
    "unit": { "type": "keyword" },
    "sketch": { "type": "text", "analyzer": "ik_smart" }, 
    "keywords": { "type": "text", "analyzer": "ik_smart" },
    "tags": { "type": "keyword" },
    "barcode": { "type": "keyword" },
    "price": { "type": "scaled_float", "scaling_factor": 100 },
    "market_price": { "type": "scaled_float", "scaling_factor": 100 },
    "rating": { "type": "float" },
    "sold_count": { "type": "integer" },
    "review_count": { "type": "integer" },    
    "virtual_retail_num": { "type": "integer" },
    "description": { "type": "text", "analyzer": "ik_smart" },
    "stock": { "type": "integer" },    
    "warning_stock": { "type": "integer" },   
    "main_image": { "type": "keyword" },
    "slider_image": { "type": "keyword" },
    "status": { "type": "integer" },
    "is_hot": { "type": "integer" },
    "sort": { "type": "integer" },
    "categories": {
      "type": "nested",
      "properties": {
        "id": { "type": "integer", "copy_to": "categories_id" },
        "pid": { "type": "integer" },
        "name": { "type": "text", "analyzer": "ik_smart", "copy_to": "categories_name" }, 
        "description": { "type": "text", "analyzer": "ik_smart", "copy_to": "categories_description" },
        "status": { "type": "integer" },
        "level": { "type": "integer" },
        "img": { "type": "keyword" }
      }
    },    
    "brand": {
      "type": "nested",
      "properties": {
        "id": { "type": "integer" },
        "name": { "type": "text", "analyzer": "ik_smart", "copy_to": "brand_name" }, 
        "description": { "type": "text", "analyzer": "ik_smart", "copy_to": "brand_description" },
        "log_url": { "type": "keyword" },
        "img": { "type": "keyword" }
      }
    },      
    "attrs": {
      "type": "nested",
      "properties": {
        "id": { "type": "integer" },
        "name": { "type": "keyword", "copy_to": "attrs_name" }
      }
    },  
    "skus": {
      "type": "nested",
      "properties": {
        "id": { "type": "integer" },
        "name": { "type": "text", "analyzer": "ik_smart"}, 
        "main_url": { "type": "keyword" },
        "price": { "type": "scaled_float", "scaling_factor": 100 },
        "sold_count": { "type": "integer" }
      }
    }
  }
}'

  • 提交数据中的 properties 代表这个索引中各个字段的定义,其中 key 为字段名称,value 是字段的类型定义
  • type 定义了字段的数据类型,常用的有 text / integer / date / boolean ,还有更多类型
    • keyword,这是字符串类型的一种,这种类型是告诉 Elasticsearch 不需要对这个字段做分词,通常用于邮箱、标签、属性等字段。
    • scaled_float 代表一个小数位固定的浮点型字段,与 Mysql 的 decimal 类型类似。
    • scaling_factor 用来指定小数位精度,100 就代表精确到小数点后两位。
    • nested 代表这个字段是一个复杂对象,由下一级的 properties 字段定义这个对象的字段。
  • analyzer 称为分词器,这是告诉 Elasticsearch 应该用什么方式去给这个字段做分词,这里我们用了 ik 中文分词插件,(ik_max_word:会将文本做最细粒度的拆分;ik_smart:会做最粗粒度的拆分)。
  • copy_to,Elasticsearch 的多字段匹配查询是不支持查询 Nested 对象的字段,但是我们又必须查询 categories.name 字段,因此我们可以使用 copy_to 参数,可以将 categories.name 字段复制到上层,我们就可以通过 categories_name 字段做多字段匹配查询

查看 type


curl -X GET "http://localhost:9200/{index_name}/_mapping"

创建文档 Document (新增一条记录)

更新数据和创建数据是一样的接口,更新数据时,就是使用 PUT 请求将数据重新发送一次

对应的接口地址是 /{index_name}/_doc/{id} 这里的 id 和 mysql 中的 id 不一样,不是自增的,需要我们手动指定(它不一定是数字,任意字符串即可)。


# 新增记录的时候,也可以不指定 ID,但是此时就要发送 POST 请求(此时产生的 _id 字段就是一个随机字符串)
curl -H 'Content-Type: application/json' -X POST http://localhost:9200/test_index/_doc -d '{
    "title": "iPhone 7P",
    "description": "iphone 第一批双摄像头",
    "price": 6799
}'

# 创建 id 为 1 的文档
curl -H 'Content-Type: application/json' -X PUT http://localhost:9200/test_index/_doc/1?pretty -d'{
    "title": "iPhone 7P",
    "description": "iphone 第一批双摄像头",
    "price": 6799
}'

# 会返回如下内容
{
  "_index" : "test_index",
  "_type" : "_doc",
  "_id" : "1",
  "_version" : 1,
  "result" : "created",
  "_shards" : {
    "total" : 2,
    "successful" : 1,
    "failed" : 0
  },
  "_seq_no" : 0,
  "_primary_term" : 2
}


# 创建 id 为 2 的文档
curl -H'Content-Type: application/json' -XPUT http://localhost:9200/test_index/_doc/2?pretty -d'{
    "title": "OPPO find x",
    "description": "高清像素",
    "price": 3499
}'

# 会返回如下内容
{
  "_index" : "test_index",
  "_type" : "_doc",
  "_id" : "2",
  "_version" : 1,
  "result" : "created",
  "_shards" : {
    "total" : 2,
    "successful" : 1,
    "failed" : 0
  },
  "_seq_no" : 1,
  "_primary_term" : 2
}

读取文档数据 (查看一条记录)


curl http://localhost:9200/test_index/_doc/1?pretty=true

# 会返回如下内容
{
  "_index" : "test_index",
  "_type" : "_doc",
  "_id" : "1",
  "_version" : 1,
  "_seq_no" : 0,
  "_primary_term" : 2,
  "found" : true,  // found 字段为 true 表示查询成功,为 false 表示查不到数据
  "_source" : {
    "title" : "iPhone 7P",
    "description" : "iphone 第一批双摄像头",
    "price" : 6799
  }
}

删除文档数据 (删除一条记录)


curl -X DELETE http://localhost:9200/test_index/_doc/1

查看 Elasticsearch 索引中有多少条数据

对应的接口地址为 /{index_name}/_doc/_count


curl http://localhost:9200/test_index/_doc/_count\?pretty

# 会返回如下内容
{
  "count" : 3,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  }
}

查看所有记录


curl http://localhost:9200/test_index/_doc/_search?pretty=true

简单搜索


# 指定的匹配条件是 `description` 字段里面包含 `iphone` 这个词
curl -XPOST -H'Content-Type:application/json' http://localhost:9200/test_index/_doc/_search\?pretty -d'
{
    "query" : { "match" : { "description" : "iphone" }}
}'

# 会返回如下内容
{
  "took" : 16,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 1,
      "relation" : "eq"
    },
    "max_score" : 0.60996956,
    "hits" : [
      {
        "_index" : "test_index",
        "_type" : "_doc",
        "_id" : "1",
        "_score" : 0.60996956,
        "_source" : {
          "title" : "iPhone 7P",
          "description" : "iphone 第一批双摄像头",
          "price" : 6799
        }
      }
    ]
  }
}


# es 默认一次返回 10 条结果,可以通过 size 字段来重新设置,比如以下每次只返回 3 条结果
curl -X POST -H 'Content-Type:application/json' http://localhost:9200/test_index/_doc/_search\?pretty -d'
{
    "query" : { "match" : { "description" : "iphone" }},
    "size": 3
}'


# 指定偏移量,默认的 from 为 0
curl -X POST -H 'Content-Type:application/json' http://localhost:9200/test_index/_doc/_search\?pretty -d'
{
    "query" : { "match" : { "description" : "iphone" }},
    "from": 2,
    "size": 3
}'

# 逻辑或,如果有多个搜索关键词,那么 es 认为是 or 关系
# 查询关键字 `iphone` 或者 `手机` 的记录
curl -X POST -H 'Content-Type:application/json' http://localhost:9200/test_index/_doc/_search\?pretty -d'
{
    "query" : { "match" : { "description" : "iphone 手机" }}
}'

# 逻辑且,需要使用布尔查询
curl -X POST -H 'Content-Type:application/json' http://localhost:9200/test_index/_doc/_search\?pretty -d'
{
    "query": {
        "bool": {
            "must": [
                {"match": {"desc": "iphone"}},
                {"match": {"desc": "手机"}}
            ]
        }
    }
}'

相关文章

网友评论

      本文标题:一文弄懂 ElasticSearch 使用

      本文链接:https://www.haomeiwen.com/subject/kqdzodtx.html