在ecto 3.0中选择合并

时间:2018-10-30 08:56:34

标签: elixir ecto

我正在实现选择合并,以构建用于聚合函数的查询。这是我的代码

Enum.reduce(opts_aggregate, queryable, fn {aggregate_type, fields}, 
  queryable ->
    case aggregate_type do
      "$max" ->
        case fields do
          fields when is_list(fields) ->
            Enum.reduce(fields, queryable, fn field, queryable ->
              build_max(queryable, field)
            end)

          field when is_binary(field) ->
            build_max(queryable, field)
        end

      "$min" ->
        case fields do
          fields when is_list(fields) ->
            Enum.reduce(fields, queryable, fn  field, queryable ->
              build_min(queryable, field)
            end)

          field when is_binary(field) ->
            build_min(queryable, field)
        end
 end)


def build_max(queryable, field) do
  field = Helper.string_to_atom(field)

from(q in queryable,
   select_merge:  %{"$aggregate": %{"$max": %{^field => max(field(q, ^field))}}}
)
end

def build_min(queryable, field) do
  field = Helper.string_to_atom(field)

  from(q in queryable,
    select_merge:  %{"$aggregate": %{"$min": %{^field =>min(field(q,^field))}}}
)

结束

这些参数是:

   opts = %{
     "$aggregate" => %{    
       "$max" => "level",
       "$min" => "beds"
     }
  }  

这是我得到的查询:

select: merge(merge(f, %{"$aggregate": %{"$max": %{^:level => max(f.level)}}}), %{"$aggregate": %{"$min": %{^:level => min(f.beds)}}})>

在两个查询中我都得到了level键。

  %{"$max": %{^:level => max(f.level)
   %{"$min": %{^:level => min(f.beds)

我做错什么了吗?还是这是问题?

是否有可能代替查询中的多个嵌套合并?我只是这样获得查询:

select: merge(f, %{"$aggregate": %{"$max": %{^:level => max(f.level)}}}), %{"$aggregate": %{"$min": %{^:level => min(f.beds)}}})>

谢谢

0 个答案:

没有答案