[TOC] ## 新增记录 ### 以 PUT 方式,需要在url 中添加id ``` $ curl -X PUT 'localhost:9200/accounts/person/1' -d ' { "user": "张三", "title": "工程师", "desc": "数据库管理" }' ``` 返回 ``` { "_index":"accounts", "_type":"person", "_id":"1", "_version":1, "result":"created", "_shards":{"total":2,"successful":1,"failed":0}, "created":true } ``` ### 以post 方式 ,不需要加 id 自动生成的id 是个随机数 ``` $ curl -X POST 'localhost:9200/accounts/person' -d ' { "user": "李四", "title": "工程师", "desc": "系统管理" }' ``` 返回 ``` { "_index":"accounts", "_type":"person", "_id":"AV3qGfrC6jMbsbXb6k1p", "_version":1, "result":"created", "_shards":{"total":2,"successful":1,"failed":0}, "created":true } ``` > 生成数据时如果没有先创建 index 即`accounts`也不会报错,而是直接手动生成对应的index ## 查看记录 `curl 'localhost:9200/accounts/person/1?pretty=true'` - pretty=true 返回易读的格式 - accounts/person/1 id 为1 success ``` { "_index" : "accounts", "_type" : "person", "_id" : "1", "_version" : 1, "found" : true, "_source" : { "user" : "张三", "title" : "工程师", "desc" : "数据库管理" } } ``` error ``` { "_index" : "accounts", "_type" : "person", "_id" : "abc", "found" : false } ``` ## 删除记录 ` curl -X DELETE 'localhost:9200/accounts/person/1'` ## 更新记录 ``` $ curl -X PUT 'localhost:9200/accounts/person/1' -d ' { "user" : "张三", "title" : "工程师", "desc" : "数据库管理,软件开发" }' ``` 返回值 ``` { "_index":"accounts", "_type":"person", "_id":"1", "_version":2, //版本信息发送变化 "result":"updated", "_shards":{"total":2,"successful":1,"failed":0}, "created":false } ``` ## 查询 ### 返回所有记录 `curl 'localhost:9200/accounts/person/_search'` ``` { "took":2, "timed_out":false, "_shards":{"total":5,"successful":5,"failed":0}, "hits":{ "total":2, "max_score":1.0, "hits":[ ... took 返回记录数,本例是2条。 max_score:最高的匹配程度,本例是1.0。 hits:返回的记录组成的数组 ``` ### 全文搜索 GET 请求带有数据体 ``` $ curl 'localhost:9200/accounts/person/_search' -d ' { "query" : { "match" : { "desc" : "软件" }}, "from": 1, "size": 1 //Elastic 默认一次返回10条结果 }' ``` ### 逻辑运算 ``` $ curl 'localhost:9200/accounts/person/_search' -d ' { "query" : { "match" : { "desc" : "软件 系统" }} }' ``` 使用 or 查询 如果要使用 and 可使用下面的方式 ``` curl 'localhost:9200/accounts/person/_search' -d ' { "query": { "bool": { "must": [ { "match": { "desc": "软件" } }, { "match": { "desc": "系统" } } ] } } }' ``` ## 聚合查找 Elasticsearch 的聚合操作有两个主要的概念: * 桶(Buckets):满足特定条件的文档的集合 * 指标(Metrics):对桶内的文档进行统计计算 桶的概念上类似于 SQL 的分组(`group by`),而指标类似于`count()`、`sum()`、`max()`等统计方法 ### 字符串开启聚合 默认情况下,文本字段禁用Fielddata。 在[name]上设置fielddata=true,以便通过取消反转索引来在内存中加载fielddata。 但是请注意,这可能会占用大量内存。 或者使用关键字字段 ### Terms 将一个或多个字段分组 ``` { "size" : 0, "aggs": { "terms_classNo": { "terms": { "field": "classNo" } } } } ``` > **terms_classNo** 是自定义变量名,将会在返回值中展示,**classNo** 为字段名 ### Range ``` { "size" : 0, "aggs": { "range_age": { "range": { "field": "age", "ranges": [ { "to": 10 }, { "from": "11", "to": "15" }, { "from": "16" } ] } } } } ``` ## Metrics(指标) 如 sum , max 等 ``` { "size" : 0, "aggs" : { "avg_grade" : { "terms": { "field": "classNo" }, "aggs": { "avg_grade": { "avg": {"field": "price"} } } } } } ```