1. 程式人生 > >常用mysql語句轉elasticsearch查詢語句

常用mysql語句轉elasticsearch查詢語句

  1. 多個查詢條件 bool(must、should、must_not)
select * from index_person where name = 'jeck' or sex = 'male' order by age,sex
{
	"query":{
		"bool":{
			"should":{
				{"match":{"name": "jeck"}},
				{"match": {"sex": "male"}},
			}
		}		
	},
    "sort":[{"age":{"order":"asc"},
			{"sex":{"order":"desc"}}]
}
  1. like查詢 wildcard
select * from index_person where name like '%jeck%'

{
	"query":{
		"bool":{
			"must":{
				"wildcard":{
					"name":"*jeck*"
				}
			}
		}		
	}
}
  1. 區間查詢 range
select * from index_person where name = 'jeck' and sex = 'male' and (age<30 and age>40)

{
 "query": {
    "bool": {
		"must": [
			{"match":{"name": "jeck"}},
			{"match": {"sex": "male"}},
			{"range" : {"age" : {"gt" : 40,"lt":30}}}
		]
    }
  }
}
  1. 根據bucket提取彙總數,如果對彙總數繼續分組,可以在group_by_sex後繼續新增aggs結構
select count(sex) from index_person where age>30 group by sex;

{
  "size":10,
  "query":{
    "bool":{
      "must":[{"range" : {"age" : {"gt" : 30}}}]
    }
  },
  "aggs":{
    "group_by_sex":{
      "terms":{
        "field":"sex"
      }
    }
  }
}
  1. 分組呼叫內建函式,(avg,sum)
select average(age) from index_person  group by sex 
{
  "size":10,
  "aggs":{
    "avg_by_age":{
      "avg":{
        "field":"sex"
      }
    }
  }
}