结构化搜索 | Structured Search
- 结构化搜索是指对结构化数据的搜索;
- 日期、布尔类型和数字都是结构化的;
- 文本也可以是结构化的:
- 彩色笔可以有离散的颜色集合:红、绿、蓝
- 一个博客可能被标记了标签,例如:分布式、搜索
- 电商网站上的商品都有 UPCs 或其他的唯一标识,它们都需要遵从严格规定的,结构化的格式;
ElasticSearch 中的结构化搜索
- 布尔、日期、时间和数字这类结构化的数据,有精确的格式,可以对这些格式进行逻辑操作,包括比较数字和时间的范围,判定两个值的大小;
- 结构化的文本可以做到精确匹配或者部分匹配
- 结构化结果只能有“是”和“否”两个值
- 根据场景需要,可以决定结构化搜索是否需要打分;
结构化搜索 |举几个栗子
准备数据
- 数据字段的类型有:布尔,时间,long,字符串,这些数据都是结构化的数据;
DELETE products
POST /products/_bulk
{ "index": { "_id": 1 }}
{ "price" : 10,"avaliable":true,"date":"2018-01-01", "productID" : "XHDK-A-1293-#fJ3" }
{ "index": { "_id": 2 }}
{ "price" : 20,"avaliable":true,"date":"2019-01-01", "productID" : "KDKE-B-9947-#kL5" }
{ "index": { "_id": 3 }}
{ "price" : 30,"avaliable":true, "productID" : "JODL-X-1937-#pV7" }
{ "index": { "_id": 4 }}
{ "price" : 30,"avaliable":false, "productID" : "QQPX-R-3956-#aD8" }
GET products/_mapping
对布尔型的值做结构化的搜索
POST products/_search
{
"profile": "true",
"explain": true,
"query": {
"term": {
"avaliable": true
}
}
}
布尔型的值做结构化的搜索 | 跳过算分
POST products/_search
{
"profile": "true",
"explain": true,
"query": {
"constant_score": {
"filter": {
"term": {
"avaliable": true
}
}
}
}
}
数字类型的 Range 查询
POST products/_search
{
"query": {
"constant_score": {
"filter": {
"terms": {
"price": [
"20",
"30"
]
}
}
}
}
}
对日期类型进行 Range 查询
- y - 年
- M - 月
- w - w
- d - 天
- H / h - 小时
- m - 分钟
- s - 秒
POST products/_search
{
"query" : {
"constant_score" : {
"filter" : {
"range" : {
"date" : {
"gte" : "now-1y"
}
}
}
}
}
}
通过 Exist 查询找到非空的值
POST products/_search
{
"query": {
"constant_score": {
"filter": {
"exists": {
"field": "date"
}
}
}
}
}
多值查询 | Term 查询
- Term 查询是包含而不是等于,会查出字段 genre 中包含 Comedy 的所有数据;
POST /movies/_bulk
{ "index": { "_id": 1 }}
{ "title" : "Father of the Bridge Part II","year":1995, "genre":"Comedy"}
{ "index": { "_id": 2 }}
{ "title" : "Dave","year":1993,"genre":["Comedy","Romance"] }
POST movies/_search
{
"query": {
"constant_score": {
"filter": {
"term": {
"genre.keyword": "Comedy"
}
}
}
}
}