查询字符串为空时返回所有文档

Returning all documents when query string is empty

假设我有以下映射:

{
    'properties': {
        {'title': {'type': 'text'},
        {'created': {'type': 'text'}}
    }
}

有时用户会按created查询,有时会按titlecreated查询。在这两种情况下,我都希望查询 JSON 尽可能相似。当用户不使用 title 查询时,创建仅按 created 过滤的查询的好方法是什么?

我试过类似的方法:

    {
        bool: {
            must: [
                {range: {created: {gte: '2010-01-01'}}}, 
                {query: {match_all: {}}}
            ] 
        }
    }

但这没有用。编写此查询的最佳方式是什么?

您的查询无效,因为 created 的类型为 text 而不是 date,字符串日期的范围查询将无法按预期工作,您应该将映射从输入 textdate 并重新索引您的数据。

按照 this 逐步重新索引您的数据(使用新映射)。

现在,如果我理解正确的话,您想使用一个通用查询,它根据用户输入过滤 title or/and created

在这种情况下,我的建议是使用Query String

一个例子(版本 7.4.x):

映射

PUT my_index
{
  "mappings": {
    "properties": {
      "title": {
        "type": "text"
      },
      "created": {  -------> change type to date instead of text
        "type": "date"
      }
    }
  }
}

索引几个文件

PUT my_index/_doc/1
{
  "title":"test1",
  "created": "2010-01-01"
}

PUT my_index/_doc/2
{
  "title":"test2",
  "created": "2010-02-01"
}

PUT my_index/_doc/3
{
  "title":"test3",
  "created": "2010-03-01"
}

搜索查询(已创建)

GET my_index/_search
{
 "query": {
   "query_string": {
     "query": "created:>=2010-02-01",
     "fields"  : ["created"]
   }
 } 
}

结果

"hits" : [
      {
        "_index" : "my_index",
        "_type" : "_doc",
        "_id" : "2",
        "_score" : 1.0,
        "_source" : {
          "title" : "test2",
          "created" : "2010-02-01"
        }
      },
      {
        "_index" : "my_index",
        "_type" : "_doc",
        "_id" : "3",
        "_score" : 1.0,
        "_source" : {
          "title" : "test3",
          "created" : "2010-03-01"
        }
      }]

搜索查询(标题)

GET my_index/_search
{
 "query": {
   "query_string": {
     "query": "test2",
     "fields"  : ["title"]
   }
 } 
}

结果

"hits" : [
  {
    "_index" : "my_index",
    "_type" : "_doc",
    "_id" : "2",
    "_score" : 0.9808292,
    "_source" : {
      "title" : "test2",
      "created" : "2010-02-01"
    }
  }
]

搜索查询(标题和创建)

GET my_index/_search
{
 "query": {
   "query_string": {
     "query": "(created:>=2010-02-01) AND test3"
   }
 } 
}

结果

"hits" : {
"total" : {
  "value" : 1,
  "relation" : "eq"
},
"max_score" : 1.9808292,
"hits" : [
  {
    "_index" : "my_index",
    "_type" : "_doc",
    "_id" : "3",
    "_score" : 1.9808292,
    "_source" : {
      "title" : "test3",
      "created" : "2010-03-01"
    }
  }
]

查询字符串中的字段 - 您可以同时提及这两个字段。如果您删除 fields,则查询将应用于您映射中的所有字段。

希望对您有所帮助