Elasticsearch是什么?
- 文档型数据库,使用JSON存储数据
- 支持分布式,可以扩展到上百台服务器,处理PB级结构化或非结构化数据
- 实时分析搜索引擎,基于Lucene,可以进行全文搜索
- 使用RESTful API和客户端进行交互
文档型数据库
Elasticsearch是面向文档(document oriented)的,使用JSON格式保存数据,文档中的属性可以建立索引(index)进行索引、搜索、排序、过滤。
一个JSON文档示例:
{
"email": "john@smith.com",
"first_name": "John",
"last_name": "Smith",
"info": {
"bio": "Eco-warrior and defender of the weak",
"age": 25,
"interests": [ "dolphins", "whales" ]
},
"join_date": "2014/05/01"
}
Elasticsearch中的表、字段这些名称和关系型数据库有些区别,下面是对照表:
Relational DB | Elasticsearch | ||
数据库 | Databases | Indices | 索引 |
表 | Tables | Types | 类型 |
行 | Rows | Documents | 文档 |
列 | Columns | Fields | 字段 |
Elasticsearch和客户端的交互
我们的程序和ElasticSearch进行交互,使用HTTP请求,REST FULL方式。
下面假设要更新ElasticSearch中blog数据库 -> account表 -> 用户ID为1的用户信息,发送如下HTTP请求到ElasticSearch服务器:
PUT /blog/account/1
{
"user_name" : "John",
"age" : 25,
"about" : "I love to go rock climbing",
}
要查询用户ID等于1的用户信息,发送如下HTTP请求:
GET /blog/account/1
查询数据使用下面的HTTP请求:
GET /blog/account/_search?q=user_name:John
会收到响应:
{
"took": 6,
"timed_out": false,
"_shards": { ... },
"hits": {
"total": 3, //查询到的数量
"max_score": 1,
"hits": [ //查询到的数据
{
"_index": "blog", //数据所在的索引
"_type": "account", //所在的类型
"_id": "1",
"_score": 1,
"_source": { //具体数据集合
"user_name": "John",
"age": 35,
"about": "I like to build cabinets"
}
},
{ ... }
]
}
}
DSL语句查询
除了通过HTTP请求中带参数的方式 (/blog/account/_search?q=user_name:John)进行查询,ES还支持叫做DSL语句的查询方式,也就是将 QueryString 中的参数放到 HTTP 请求的BODY里面,通过JSON格式传递,这样能够方便的组织更复杂的查询条件。
来看一个DSL查询示例,使用 match 语句定义查询条件:
GET /blog/account/_search
{
"query" : {
"match" : {
"user_name" : "Smith"
}
}
}
.NET 中访问 ES
Elasticsearch有2个.Net client,Elasticsearch.Net
和 NEST。
Elasticsearch.Net:底层客户端程序,通过
json/request/response 和 Elasticsearch服务端进行交互。NEST:高级客户端程序,支持request和response类型映射、DSL查询。依赖 Elasticsearch.Net 。
参考文档: