Elasticsearch:如何为含双键的对象构建搜索查询?
Elasticsearch 查询构建方案
通用DSL查询语句
要精准匹配organization_size.start=0且organization_size.end=99的文档,需用布尔查询(bool query)的must子句同时指定两个精确匹配条件:
{ "query": { "bool": { "must": [ { "term": { "organization_size.start": 0 } }, { "term": { "organization_size.end": 99 } } ] } } }
Ruby on Rails 实现示例
基于elasticsearch-rails gem,可结合前端传入的参数动态构建查询:
# 从URL参数中提取筛选值 start_size = params.dig(:filters, :organization_size, 0, :key, :start)&.to_i end_size = params.dig(:filters, :organization_size, 0, :key, :end)&.to_i # 构建查询DSL search_query = { query: { bool: { must: [ { term: { "organization_size.start": start_size } }, { term: { "organization_size.end": end_size } } ] } } } # 执行查询(假设你的模型已集成Elasticsearch,比如Product) matched_results = Product.search(search_query)
关键说明
- 使用
term查询是因为需要精确匹配数值类型字段,如果你的start/end被定义为文本类型,可替换为match查询,但数值类型下term的性能和准确性更优。 - 若前端可能传入多组
organization_size筛选规则,可通过循环遍历参数数组,动态向must子句中添加匹配条件。
内容的提问来源于stack exchange,提问作者Lloyd Banks
相关产品推荐
相关产品推荐

