天天看点

分布式系列教程(33) -ElasticSearch DSL语言查询与过滤

ES中的查询请求有两种方式,一种是简易版的查询,另外一种是使用JSON完整的请求体,叫做结构化查询(DSL)。由于DSL查询更为直观也更为简易,所以大都使用这种方式。

DSL查询是POST过去一个JSON,由于POST的请求是JSON格式的,所以存在很多灵活性,也有很多形式。

下面来举些例子:

1. 根据名称精准查询姓名

GET user_dao/user/_search
{
  "query": {
    "term": {
      "name": "father"
    }
    
  }
}
      

返回内容:

分布式系列教程(33) -ElasticSearch DSL语言查询与过滤

注意:term是代表完全匹配,即不进行分词器分析,文档中必须包含整个搜索的词汇。

2. 根据名称模糊查询姓名

GET /user_dao/user_table/_search
{
  "from": 0,
  "size": 3, 
  "query": {
    "match": {
        "name": "grand"
      }
  }
}
      

返回结果:

  • name为grand的所有文档。

注意:

  • 「Match」相当于模糊匹配,只包含其中一部分关键词就行。
  • 「Match」会根据该字段的分词器,进行分词查询,而「Term」查询不会对字段进行分词查询,会采用精确匹配。
GET /user_dao/user_table/_search
{
	"query": {
		"bool": {
			"must": [{
				"match_all": {}
			}],
			"filter": {
				"range": {
					"age": {
						"gt": 20,
						"lte": 60
					}
				}

			}

		}

	},
	"from": 0,
	"size": 10,
	"_source": ["name", "age"]

}
      
{
  "took": 17,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": 4,
    "max_score": 1,
    "hits": [
      {
        "_index": "user_dao",
        "_type": "user_table",
        "_id": "5",
        "_score": 1,
        "_source": {
          "name": "grandmother",
          "age": 58
        }
      },
      {
        "_index": "user_dao",
        "_type": "user_table",
        "_id": "2",
        "_score": 1,
        "_source": {
          "name": "father",
          "age": 26
        }
      },
      {
        "_index": "user_dao",
        "_type": "user_table",
        "_id": "4",
        "_score": 1,
        "_source": {
          "name": "grandfather",
          "age": 60
        }
      },
      {
        "_index": "user_dao",
        "_type": "user_table",
        "_id": "3",
        "_score": 1,
        "_source": {
          "name": "mother",
          "age": 24
        }
      }
    ]
  }
}
      

继续阅读