elastic search 简称es, 支持restful api。具体也就是get、put、post、delete几种http的操作。
es有index、type、document、field几种概念,index(或者复数indices)类似数据库,type类似表名, document类似记录(row), field类似column。
es的restful api类似:http://localhost:9200/index/document/xxx
比如我们通过C#的NEST库的ElasticClient创建了一个index 为metric_2018_04_28_14, type为basemetric的多条document, 然后上传到es服务器中。
则get访问方式类似:
get http://localhost:9200/metric_20180428/_search
_search用来简单查询index下所有的document, 因为我们事先并不知道每个document的具体_id, 只能模糊查询看所有的结果。
返回值类似:

接下来我们就可以试试:
get http://localhost:9200/metric_2018_04_28_14/basemetrics%601/zLTXCmMBtAo_lFeNm0hM

当然除了_search这种简单的全局搜索, 我们还可以通过url传递query string, 比如下面:
http://localhost:9200/metric_2018_04_28_14/_search?q=province:%E8%8B%8F
用"q="传递关键字,比如"q=province:苏", 来查询所有包含”苏“的省份, 为什么不是”江苏“,因为如果是”江苏“会被默认分词成”江“”苏“, 然后”浙江“”江苏“都可以被模糊查询上 到。
pretty可以让es返回的json string按照pretty-print格式完美的输出。
http://localhost:9200/metric_2018_04_28_14/_search?pretty
"q="是用具体的值来过滤哪些文档符合, 而如果我们希望只返回具体的某些字段, 需要用到"_source"
http://localhost:9200/metric_2018_04_28_14/_search?_source=productNumber,serialNumber

如果仅仅指定_source, 则只返回对象本身的字符串。格式为: index/type/id/_source
http://localhost:9200/metric_2018_04_28_14/basemetrics%601/zLTXCmMBtAo_lFeNm0hM/_source

上面介绍的是简单查询字符串搜索,其实呢es支持更强大的DSL查询, 比如上面“q=江”, 转换成DSL为:
GET metric_2018_04_28_14/_search
{
"query": {
"match": {
"province": "苏"
}
}
}
上面DSL复制到到kibana的Dev Tools执行结果和url执行结果一致。

“match"的用法, filed指定document里的某个字段, TEXT指定希望的值。如果希望是精确查询而不是模糊查询, 用”match_all“代替。
"match": {
"FIELD": "TEXT"
}
es中有aggregation(聚合) 的概念, 类似于分组,也就是sql中group by类似的功能。
比如上面的type (basemetrics), 我们按照province分组统计, 最终语句如下:
GET ct_metric_2018_04_28_14/_search
{
"aggs": {
"all_province": {
"terms": {
"field": "province.keyword"
}
}
}
}
