在Elasticsearch中,提供了功能丰富的RESTful API的操作,包括基本的CRUD、创建索引、删除索引等操作。
1.创建非结构化索引
在Lucene中,创建索引是需要定义字段名称以及字段的类型的,在Elasticsearch中提供了非结构化的索引,就是不需要创建索引结构,即可写入数据到索引中,实际上在Elasticsearch底层会进行结构化操作,此操作对用户是透明的。
创建空索引:
PUT /haoke{"settings": {"index": {"number_of_shards": "2","number_of_replicas": "0"}}}返回:{"acknowledged": true,"shards_acknowledged": true,"index": "haoke"}
2.插入数据
语法:
POST /{索引}/{类型}/{id}
{
数据
}
POST /haoke/user/1001{"id":1001,"name":"zhangsan","age":20,"sex":"男"}
返回:
{"_index": "haoke","_type": "user","_id": "1001","_version": 1,"result": "created","_shards": {"total": 1,"successful": 1,"failed": 0},"_seq_no": 0,"_primary_term": 1}

说明: 非结构化的索引,不需要事先创建,直接插入数据,就会默认创建索引
不指定id插入数据:
POST /haoke/user/{"id":1002,"name":"zhangsan","age":20,"sex":"男"}返回:{"_index": "haoke","_type": "user","_id": "iMYWbW4BeGrcgRMuEDq3","_version": 1,"result": "created","_shards": {"total": 1,"successful": 1,"failed": 0},"_seq_no": 1,"_primary_term": 1}
会自动生成id
3.更新数据
在ElasticSearch中,文档数据是不能修改的,但是可以通过覆盖的方式进行更新。
PUT /haoke/user/1001{"id":1001,"name":"张三","age":21,"sex":"女"}
更新结果如下:

可以看出,是覆盖的形式:

局部更新:
原理:从旧文档中检索json,修改它,删除旧文档,索引新文档
POST /haoke/user/1001/_update{"doc": {"age":55}}

4.删除数据
DELETE /haoke/user/1001

注:删除一个文档也不会立即从磁盘上移除,它只是被标记为已删除。ElasticSearch将会在你之后添加更多索引的时候才会在后台进行删除内容的清理。
5.搜索数据
1) 根据id搜索数据
GET /haoke/user/isZfHW8BeGrcgRMuqzpQ# 返回的数据如下{"_index": "haoke","_type": "user","_id": "isZfHW8BeGrcgRMuqzpQ","_version": 2,"found": true,"_source": { # 原始数据在这里"age": 123,"name": "李四","sex": 0}}
2) 搜索全部数据
GET /haoke/user/_search# 返回的数据如下{"took": 2,"timed_out": false,"_shards": {"total": 2,"successful": 2,"skipped": 0,"failed": 0},"hits": {"total": 2,"max_score": 1,"hits": [{"_index": "haoke","_type": "user","_id": "i8ZcIW8BeGrcgRMuuToO","_score": 1,"_source": {}},{"_index": "haoke","_type": "user","_id": "isZfHW8BeGrcgRMuqzpQ","_score": 1,"_source": {"age": 123,"name": "李四","sex": 0}}]}}
3) 关键字搜索数据
#查询年龄等于123的用户GET /haoke/user/_search?q=age:123# 返回的数据如下{"took": 3,"timed_out": false,"_shards": {"total": 2,"successful": 2,"skipped": 0,"failed": 0},"hits": {"total": 1,"max_score": 1,"hits": [{"_index": "haoke","_type": "user","_id": "isZfHW8BeGrcgRMuqzpQ","_score": 1,"_source": {"age": 123,"name": "李四","sex": 0}}]}}
6.DSL搜索
ElasticSearch提供丰富且灵活的查询语言叫做DSL查询(Query DSL),它允许你构建更加复杂、强大的查询
DSL(Domain Specific Language特定领域语言)以JSON请求体的形式出现
GET[POST] /haoke/user/_search{"query": {"match": {"age": "123"}}}

当前数据:
POST /haoke/user/_search{"query": {"bool": {"filter": {"range": {"age": {"gte": 30}}},"must":{"match":{"sex":"male"}}}}}

POST /haoke/user/_search{"query": {"match": {"name": "路飞 nami"}}}

7.高亮显示
POST /haoke/user/_search{"query": {"match": {"name": "路飞 nami"}},"highlight":{"fields": {"name":{}}}}

8.集合
在Elasticsearch中,支持聚合操作,类似SQL中的group by操作。
POST /haoke/user/_search{"aggs": {"all_interests": {"terms": {"field": "age"}}}}

