Elasticsearch:通过数组属性搜索多个文档

时间:2019-05-16 07:08:43

标签: elasticsearch

我正在尝试将Elasticsearch与Symfony 4结合使用。这是我的第一次尝试。

我的索引:当我跑步时,

GET app_file_dev/_search
{
  "query": {
    "match_all": {}
  }
}

我知道了

{
  "took": 2,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": 4,
    "max_score": 1,
    "hits": [
      {
        "_index": "app_file_dev",
        "_type": "file",
        "_id": "5",
        "_score": 1,
        "_source": {
          "id": 5,
          "tags": [
            "blue"
          ]
        }
      },
      {
        "_index": "app_file_dev",
        "_type": "file",
        "_id": "8",
        "_score": 1,
        "_source": {
          "id": 8,
          "tags": [
            "blue",
            "green"
          ]
        }
      },
      {
        "_index": "app_file_dev",
        "_type": "file",
        "_id": "6",
        "_score": 1,
        "_source": {
          "id": 6,
          "tags": [
            "green"
          ]
        }
      },
      {
        "_index": "app_file_dev",
        "_type": "file",
        "_id": "7",
        "_score": 1,
        "_source": {
          "id": 7,
          "tags": []
        }
      }
    ]
  }
}

我想按数组类型的标签字段进行搜索。

然后如果我跑步,

GET app_file_dev/_search
{
  "query": {
    "match": {
      "tags": {
        "query": "blue"
      }
    }
  }
}

我可以成功获取带有标签“ blue”的两个文档。

如果我跑步,

GET app_file_dev/_search
{
  "query": {
    "match": {
      "tags": {
        "query": "blue green",
        "operator": "or"
      }
    }
  }
}

我希望它返回带有标签“ blue”和“ green”的8号文件。

但是无论它是'or'还是'and'。我只有一个空数组。

我的理解有什么问题吗?

2 个答案:

答案 0 :(得分:2)

也许您正在寻找的是查询字符串?试试这个

$params = [
    'index' => 'my_index',
    'type'  => 'my_type',
    'size'  => 10,
    'body'  => [
        "query" => [
            "query_string" => [
                "default_field" => "my_field",
                "query" => "blue OR green"
            ]
        ]
    ]
];

$search = $client->search($params);
$hits = $search['hits']['hits'];

上面的代码段将在您的my_index-> my_type索引中查找数据,重点关注具有关键字蓝色绿色现在

您可以在此处参考有关查询字符串的更多详细信息:https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html

答案 1 :(得分:1)

由于您要处理数组字段,并且想要同时具有bluegreen的文档,因此您需要在布尔查询的filter / must子句中使用term query,如下所示:

{
  "query": {
    "bool": {
      "filter": [
        {
          "term": {
            "tags": "blue"
          }
        },
        {
          "term": {
            "tags": "green"
          }
        }
      ]
    }
  }
}

如果要查找具有绿色或蓝色或两者都有作为标记的文档,则可以使用terms query。查询如下:

{
  "query": {
    "bool": {
      "filter": [
        {
          "terms": {
            "tags": [
              "blue",
              "green"
            ]
          }
        }
      ]
    }
  }
}