ElasticSearch入门教程

2023-02-18  本文已影响0人  后厂村村长

简介

ElaticSearch,简称ES。
ES 是一个开源的高扩展的分布式全文检索引擎,它可以近乎实时的存储、检索数据;
其扩展性很好,可扩展到上百台服务器,处理PB级别的数据。
ES 使用Java开发并使用Lucene作为其核心来实现所有索引和搜索的功能,但是它的目的是通过简单的RESTful-API来隐藏Lucene的复杂性,从而让全文搜索变得更简单。

ES核心基础概念

ES 与 MySQL 的基本映射关系如下
MySQL ‐> database ‐> Table ‐> Rows ‐> Columns
ES ‐> index ‐> Type ‐> Documents ‐> Fields

版本变迁

type (类型) 其实是ES早期版本中的设计缺陷:

移除 type 定义,其实很好理解,本来 type 的设计就是一种冗余的存在,完全可通过为 index 添加不同后缀来区分同一业务下的不同类型;

创建索引

官网文档参考:https://www.elastic.co/guide/en/elasticsearch/reference/6.8/indices-put-mapping.html
1 、创建空索引(类似于创建mysql空库)

### 创建名为 twitter 的空索引
curl -X PUT "localhost:9200/twitter?pretty" -H 'Content-Type: application/json' -d'{}'
### 创建索引附带设置信息等
-d'
{
    "settings" : {
        "number_of_shards" : 1
    },
    "mappings" : {
        "_doc" : {
            "properties" : {
                "field1" : { "type" : "text" }
            }
        }
    }
}
'

2 、为索引添加索引字段(类似于创建mysql表)

## 注:_doc 为默认type,7.x 版本不再支持自定义,8.x 版本后移除
curl -X PUT "localhost:9200/twitter/_mapping/_doc?pretty" -H 'Content-Type: application/json' -d'
{
    "dynamic": "true", ## 允许动态根据灌入数据创建mapping
    "properties": {
        "auto_id": {
            "type": "long"
        },
        "create_date": {
            "type": "date",
            "format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd"
        },
        "student_name": {
            "type": "text", ## 设定学生姓名为文本类型
            "fields": {
                "keyword": {
                    "type": "keyword",  ## 为姓名添加 keyword 无分词索引
                    "ignore_above": 256 ## 最大索引长度256,即上限
                }
            },
            "analyzer": "ik_smart"  ## 设定学生姓名的查询分词器
        }
    }
}
'

向索引插入数据

1、 为 Twitter 索引添加名为 ·汤姆克鲁斯· 的学生

## 注:_doc/1?pretty,此处为显示指定 `id(ES内置_id)` 为 1,不指定的情况ES会自动生成 `_id` 值;
curl -X PUT "localhost:9200/twitter/_doc/1?pretty" -H 'Content-Type: application/json' -d'
{
    "student_name" : "汤姆克鲁斯",
    "create_date" : "2019-11-15",
    "auto_id" : 111
}
'

查询索引

1、查询 Twitter 索引下姓氏为 · 克鲁斯· 的学生,并按创建时间倒序,同时对检索命中的结果做高亮(highlight)展示

curl -X GET "localhost:9200/twitter/_doc/_search?pretty" -H 'Content-Type: application/json' -d'
{
    "sort": {
        "create_date": "desc"
    },
    "highlight": {
        "fields": {
            "student_name": {}
        }
    },
    "query": {
        "term": {
            "student_name.keyword": {
                "value": "克鲁斯"
            }
        }
    }
}
'
上一篇 下一篇

猜你喜欢

热点阅读