(1)match all
GET /_search
{
"query": {
"match_all": {}
}
}
(2)match
GET /_search
{
"query": {
"match": {
"title": "my elasticsearch article"
}
}
}
(3)multi match
GET /test_index/test_type/_search
{
"query": {
"multi_match": {
"query": "test",
"fields": ["test_field", "test_field1"]
}
}
}
(4)range query,可以嵌套在query中也可以嵌套在filter中
filter & query
filter,不需要计算相关度分数,不需要按照相关度分数进行排序,同时还有内置的自动cache最常使用filter的数据,性能更好
query,相反,要计算相关度分数,按照分数进行排序,而且无法cache结果
GET /company/employee/_search
{
"query": {
"range": {
"age": {
"gte": 30
}
}
}
}
(5)term query,查询条件不分词
GET /test_index/test_type/_search
{
"query": {
"term": {
"test_field": "test hello"
}
}
}
(6)terms query
GET /_search
{
"query": {
"terms": {
"tag": ["search", "full_text", "nosql"]
}
}
}
(7)bool query 多条件查询
must,must_not,should,filter
每个子查询都会计算一个document针对它的相关度分数,然后bool综合所有分数,合并为一个分数,当然filter是不会计算分数的
GET /website/article/_search
{
"bool": {
"must": {
"match": {
"title": "how to make millions"
}
},
"must_not": {
"match": {
"tag": "spam"
}
},
"should": [{
"match": {
"tag": "starred"
}
}],
"filter": {
"bool": {
"must": [{
"range": {
"date": {
"gte": "2014-01-01"
}
}
}, {
"range": {
"price": {
"lte": 29.99
}
}
}],
"must_not": [{
"term": {
"category": "ebooks"
}
}]
}
}
}
}
(8)定位不合法的语句_validate/query?explain
一般用在那种特别复杂庞大的搜索下,比如你一下子写了上百行的搜索,这个时候可以先用validate api去验证一下,搜索是否合法
GET /test_index/test_type/_validate/query?explain
{
"query": {
"math": {
"test_field": "test"
}
}
}
{
"valid": false,
"error": "org.elasticsearch.common.ParsingException: no [query] registered for [math]"
}
(9)定义排序规则
默认情况下,是按照_score降序排序的。当然,也可以是constant_score,查出来的socre都是1
GET /company/employee/_search
{
"query": {
"constant_score": {
"filter": {
"range": {
"age": {
"gte": 30
}
}
}
}
},
"sort": [{
"join_date": {
"order": "asc"
}
}]
}
(10)field建立两次索引,解决分词排序问题
如果对一个string field进行排序,结果往往不准确,因为分词后是多个单词,再排序就不是我们想要的结果了
通常解决方案是,将一个string field建立两次索引,一个分词,用来进行搜索;一个不分词,用来进行排序。
fielddata 是否建立正排索引
PUT /website
{
"mappings": {
"article": {
"properties": {
"title": {
"type": "text",
"fields": {
"raw": {
"type": "keyword"
}
},
"fielddata": true
},
"content": {
"type": "text"
},
"post_date": {
"type": "date"
},
"author_id": {
"type": "long"
}
}
}
}
}
PUT /website/article/1
{
"title": "first article",
"content": "this is my second article",
"post_date": "2017-01-01",
"author_id": 110
}
GET /website/article/_search
{
"query": {
"match_all": {}
},
"sort": [{
"title.raw": {
"order": "desc"
}
}]
}