(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二汛,不需要計算相關(guān)度分?jǐn)?shù),不需要按照相關(guān)度分?jǐn)?shù)進行排序肴颊,同時還有內(nèi)置的自動cache最常使用filter的數(shù)據(jù),性能更好
query授瘦,相反竟宋,要計算相關(guān)度分?jǐn)?shù),按照分?jǐn)?shù)進行排序丘侠,而且無法cache結(jié)果
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針對它的相關(guān)度分?jǐn)?shù)担神,然后bool綜合所有分?jǐn)?shù)始花,合并為一個分?jǐn)?shù),當(dāng)然filter是不會計算分?jǐn)?shù)的
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
一般用在那種特別復(fù)雜龐大的搜索下亥贸,比如你一下子寫了上百行的搜索浇垦,這個時候可以先用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)定義排序規(guī)則
默認(rèn)情況下朴摊,是按照_score降序排序的。當(dāng)然甚纲,也可以是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進行排序这溅,結(jié)果往往不準(zhǔn)確悲靴,因為分詞后是多個單詞臭胜,再排序就不是我們想要的結(jié)果了
通常解決方案是癞尚,將一個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"
}
}]
}