mapping:
PUT movies
{
"mappings": {
"properties": {
"title": {
"type": "text",
"fields": {
"original": {
"type": "keyword"
}
}
},
"synopsis": {
"type": "text"
},
"actors": {
"type": "text"
},
"director": {
"type": "text"
},
"rating": {
"type": "half_float"
},
"release_date": {
"type": "date",
"format": "dd-MM-yyyy"
},
"certificate": {
"type": "keyword"
},
"genre": {
"type": "text"
}
}
}
}
精确查询,对于查询字段不会使用分词器拆分
GET /movies/_search
{
"query": {
"term": {
"title": {
"value": "The Shawshank Redemption" //查询字段不分词
}
}
}
}
当使用 term查询,虽然文档中有这条数据,但是使用这个查询却返回为空
因为索引中title字段的类型是text, text 类型在写入的过程中就被分词,并且存储在索引中。 term queries are not suitable when working with text field, they are intended to be used on non text fields like keywords, numericals, and dates.
换成下面就可以查询到
GET /movies/_search
{
"query": {
"term": {
"title.keyword": "The Shawshank Redemption"
}
}
}
多个 term 查询
GET /movies/_search
{
"query": {
"terms": {
"title.keyword": [
"The Shawshank Redemption",
"The Godfather"
]
}
}
}
GET /movies/_search
{
"query": {
"ids": {
"values": [1,2,3]
}
}
}
查询索引中是字段field是否存在
GET /movies/_search
{
"query": {
"exists": {
"field": "title"
}
}
}
GET /movies/_search
{
"query": {
"range": {
"rating": {
"gte": 9,
"lte": 20
}
}
}
}
GET /movies/_search
{
"query": {
"wildcard": {
"title": {
"value": "god*"
}
}
}
}
字符 | 描述 |
---|---|
* (asterisk) | 匹配一个或多个 |
? (question mark) | 匹配单个 |
wildcard,range, prefix, fuzzy, regex, and join queries are expensive query
//关闭 昂贵查询
PUT _cluster/settings
{
"transient": {
"search.allow_expensive_queries": "false"
}
}
//关闭之后,再使用这些查询,会报错
"reason" : "[wildcard] queries cannot be executed when 'search.allow_expensive_queries' is set to false."
GET /movies/_search //查询成功
{
"query": {
"prefix": {
"title.original": {
"value": "Th"
}
}
},
"highlight": {
"fields": {
"title.original": {}
}
}
}
注意,title.original
是 keyword 类型, 如果 换成 title
为text 类型时, prefix 会查询不到
当我们记不清 是 rama
还是 dama
时,就可以使用 Fuzzy query, 可以为我们纠错,使用 fuzziness
纠错 offset
GET /movies/_search
{
"query": {
"fuzzy": {
"genre": {
"value": "rama",
"fuzziness": 1 // 这个值从左边开始计算
}
}
}
}
//结果返回 dama
{
"took": 2,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 20,
"relation": "eq"
},
"max_score": 0.23582748,
"hits": [
{
"_index": "movies",
"_id": "1",
"_score": 0.23582748,
"_source": {
"genre": "Drama "
}
}
]
}
}