You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何处理Solr facet返回的city_id结果,生成按region分组的哈希结构

实现步骤

你需要先准备两份业务映射数据,再对Solr返回的facet数组做转换分组即可,以下是Ruby实现示例:

  1. 准备前置映射字典
    这两份数据需要你根据实际业务的城市、区域对应关系自行补全:
# 映射1:city_id 对应 [城市名称, slug]
city_id_to_base_info = {
  "1" => ["北京", "beijing"],
  "2" => ["上海", "shanghai"],
  "3" => ["广州", "guangzhou"],
  # 其余city_id对应信息自行补充
}

# 映射2:city_id 对应所属区域标识(即目标结构中的:region_1这类键)
city_id_to_region_key = {
  "1" => :region_1,
  "2" => :region_1,
  "3" => :region_2,
  # 其余city_id所属区域自行补充
}
  1. 处理Solr返回的facet数组
    Solr的facet返回结果为键值交替的数组,先把它转换为city_id => 岗位数的哈希:
# 你的Solr返回的city_id facet原始数组
solr_facet_data = [
  "1",131,
  "2",96,
  "3",11,
  "4",10,
  "7",8,
  "6",6,
  "15",5,
  "10",4,
  "34",4,
  "36",3,
  "59",3,
  "71",1
]

# 转换为city_id到岗位数的映射
city_job_count_map = solr_facet_data.each_slice(2).to_h
  1. 按区域分组生成目标结构
# 初始化结果哈希,不存在的region键会自动生成空哈希作为默认值
result = Hash.new { |hash, key| hash[key] = {} }

city_job_count_map.each do |city_id, job_count|
  # 跳过未配置映射的city_id,你也可以自行添加兜底逻辑(比如归入未分类区域)
  next unless city_id_to_base_info.key?(city_id) && city_id_to_region_key.key?(city_id)
  
  region = city_id_to_region_key[city_id]
  city_info = city_id_to_base_info[city_id]
  result[region][city_info] = job_count
end

输出示例

最终得到的result结构和你要求的格式完全一致:

{
  :region_1 => {
    ["北京", "beijing"] => 131,
    ["上海", "shanghai"] => 96
  },
  :region_2 => {
    ["广州", "guangzhou"] => 11
    # 其余城市、区域依此类推
  }
}

如果你用其他编程语言实现,逻辑完全一致:先将交替排列的facet数组拆为city_id和岗位数的键值对,再通过预设的映射关联城市基础信息和所属区域,最后按区域分组整理即可。

内容的提问来源于stack exchange,提问作者Hà Mai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 04:30:04