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

问题描述 投票:0回答:1

说我有以下映射:

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

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

我尝试过类似的事情:

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

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

elasticsearch elasticsearch-5
1个回答
0
投票

您的查询无效,原因是created的类型为text而不是date,对字符串日期的范围查询将无法正常工作,您应该将映射从text更改为date,然后重新索引您的数据。

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

现在,如果我理解正确,您想使用根据用户输入过滤title或/和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,则查询将应用于映射中的所有字段。

希望这会有所帮助

© www.soinside.com 2019 - 2024. All rights reserved.