ElasticSearch匹配查询多个术语PHP

时间:2016-06-13 13:05:31

标签: php elasticsearch querydsl

我正在尝试构建必须在多个术语上查询,数组看起来像这样:

$params = [
'body' => [
    'query' => [
        "bool" => [
            "must" => [
                "terms" => [
                    "categories" => [
                        "Seating",
                    ],
                ],
                "terms" => [
                    "attributes.Color" => [
                        "Black",
                    ],
                ]
            ],
            "filter" => [
                "range" => [
                    "price" => [
                        "gte" => 39,
                        "lte" => 2999,
                    ],
                ],
            ],
        ],
    ],
    'from' => 0,
    'size' => 3,
],
];

这是用JSON表示的:

{
"query": {
    "bool": {
        "must": {
            "terms": {
                "attributes.Color": ["Black"]
            }
        },
        "filter": {
            "range": {
                "price": {
                    "gte": "39",
                    "lte": "2999"
                }
            }
        }
    }
},
"from": 0,
"size": 3
}

问题是,JSON对象在PHP中表示为数组,因此如果我为一个数组设置了键,则会重写它。您对如何在PHP中创建多个术语查询有任何想法吗?

提前致谢。

1 个答案:

答案 0 :(得分:3)

您需要添加一个额外的数组来封闭所有terms个查询

$params = [
'body' => [
    'query' => [
        "bool" => [
            "must" => [
              [
                "terms" => [
                    "categories" => [
                        "Seating",
                    ],
                ]
              ],
              [
                "terms" => [
                    "attributes.Color" => [
                        "Black",
                    ],
                ]
              ]
            ],
            "filter" => [
                "range" => [
                    "price" => [
                        "gte" => 39,
                        "lte" => 2999,
                    ],
                ],
            ],
        ],
    ],
    'from' => 0,
    'size' => 3,
],
];