Elasticsearch使用
2019年3月29日1. Elasticsearch 的基础概念
Elasticsearch 是一个非常灵活和强大的搜索引擎,涉及到非常多的概念,为了降低入门门槛,这里先给大家介绍 Elasticsearch 最最基础的一些概念。
Elasticsearch 本质上是一个数据库,但并不是 Mysql 这种关系型数据库,查询语言也不是 SQL,而且 Elasticsearch 自己的一套查询语言。
既然是数据库,有一些概念是互通的,如下表:
Mysql | Elasticsearch |
---|---|
数据库(Database) | 索引(Index) |
表(Table) | 类型(Type) |
记录(Row) | 文档(Document) |
字段(Column) | 字段(Fields) |
其中 Elasticsearch 的类型(Type)在 6.x 版本中已经被标记为 Deprecated (废弃)并将在 7.x 版本中移除。
6.x 版本的文档建议一个索引(Index)中只放一个类型(Type),可以简单理解为一个数据库中只包含一个表。这是因为在 Elasticsearch 的底层实现中,假如我们在 Type A 中定义了一个名为 status 的 integer 类型字段,在同一个 Index 下的另一个 Type B 如果也有 status 字段,那么 Type B 的 status 字段的类型也必须为 integer,否则 Type B 都无法被创建。
为了遵循这个建议,在我们之后创建的所有 Index 都将只包含一个 Type,并统一命名为 _doc
。
2. 一些基础操作
1.产看版本
1 |
$ sudo /usr/share/elasticsearch/bin/elasticsearch-plugin list -v |
2.创建索引
1 |
$ curl -XPUT http://localhost:9200/test_index |
2.1删除索引
1 |
curl -XDELETE 'localhost:9200/customer?pretty' |
3.查看索引类型
1 2 |
$ curl http://localhost:9200/test_index #压缩产看 $ curl http://localhost:9200/test_index?pretty #格式化查看 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
{ "test_index": { "aliases": {}, "mappings": {}, "settings": { "index": { "creation_date": "1553598529559", "number_of_shards": "5", "number_of_replicas": "1", "uuid": "VB4RBBVBRlqHavR6kzrxwQ", "version": { "created": "6040099" }, "provided_name": "test_index" } } } } |
3.1查看所有索引
1 |
curl 'localhost:9200/_cat/indices?v' |
4.创建类型(type) 7.0已废弃
接下来我们将在刚刚创建的索引中创建一个新的类型,对应的接口地址是 /{index_name}/_mapping/{type_name}
:
1 2 3 4 5 6 7 |
$curl -H'Content-Type: application/json' -XPUT http://localhost:9200/test_index/_mapping/_doc -d'{ "properties": { "title": { "type": "text", "analyzer": "ik_smart" }, "description": { "type": "text", "analyzer": "ik_smart" }, "price": { "type": "scaled_float", "scaling_factor": 100 } } }' |
5.创建文档(相当于mysql里的一条数据)
1 2 3 4 5 6 7 8 9 10 |
$ curl -H'Content-Type: application/json' -XPUT http://localhost:9200/test_index/_doc/1 -d'{ "title": "iPhone X", "description": "新品到货", "price": 8848 }' $ curl -H'Content-Type: application/json' -XPUT http://localhost:9200/test_index/_doc/2 -d'{ "title": "OPPO R15", "description": "新品到货", "price": 2000 }' |
6.获取指定文档
1 |
curl http://localhost:9200/test_index/_doc/1 |
7.简单的搜索
1 2 3 4 |
$ curl -XPOST -H'Content-Type:application/json' http://localhost:9200/test_index/_doc/_search -d' { "query" : { "match" : { "description" : "新" }} } |