使用通配符、范围和术语的 Elasticsearch 搜索

Elasticsearch seach using wildcard, range and terms

我正在尝试在 Elasticsearch(版本 7.1)索引上编写搜索 DSL 查询,该索引具有 product_name、exported_at 和 category_id.

等字段

从文档中我了解到我需要使用通配符、范围来搜索日期字段和术语来过滤所需的 category_id。

示例:我需要过滤 SQL 为:

的数据
SELECT * from products table
WHERE product_name LIKE '%geography%'
AND exported_at >= '2020-01-01' AND exported_at <= '2020-12-31'
AND category_id IN [10,20,30,40]

更新了以下代码:

// Creating new index
$params = [
    'index' => PS_ELASTIC_INDEX,
    'body' => [
        'mappings' => [
            'properties' => ['wc_product_name' => ["type" => "wildcard"]]
        ],
    ]
];

$response_create = $this->client->indices()->create($params);

//Storing data to the Index
//$rows contain the data fetch from the DB

foreach($rows as $row ) {
    
    $data['body'][] = [
        'id'                => $row->id,
        'wc_product_name'   => $row->product_name,
        'category_id'       => $row->category_id,
        'exported_at'       => $row->exported_at,
    ]
}

//Search the Elastic search index

$keyword  = $requestVars['product_name'];

$filters = [];

$filters[] = [
    'wildcard' => [
            'wc_product_name' => [
            'value' => '*'.$keyword.'*', 
        ],
    ]
];

$filters[] = [
    "range" => [
        "exported_on" =>  [
            "gte" => $requestVars['date_from'],
            "lte" => $requestVars['date_to'],
            "boost" => 2.0
        ]
    ],
];

if(!empty($requestVars['categories'])) {
    $filters[] = [
        "terms" => [
            "category_id" => $requestVars['categories'],
            "boost" => '1.0'
        ],
    ];
}   

$params = [
    'index' => PS_ELASTIC_INDEX,
    'body' => [
        'query' => [
            'bool' => [ 'filter' => $filters ]
        ]
    ]
];

$data = $this->client->search($params);

现在的问题是,如果使用“地理”这样的单个词作为产品名称,搜索就可以工作,而搜索“亚洲地理”这样的多个词就无法工作。

您缺少 bool/filter 查询来封装您的三个条件:

  'body' => [
      'query' => [
        'bool' => [
          'filter' => [
             [
                'wildcard' => [
                        'product_name' => [
                        'value' => "*".$keyword."*", 
                        'boost' => 1.0,
                        'rewrite' => 'constant_score'
                    ],
                ]
             ],
             [
                "range" => [
                    "exported_on" =>  [
                        "gte" => $requestVars['date_from'],
                        "lte" => $requestVars['date_to'],
                        "boost" => 2.0
                    ]
                ],
             ],
             [
                "terms" => [
                    "category_id" => [10,20,30,40],
                    "boost" => '1.0'
                ]
             ],
          ]
      ]
   ]
 ]