1

I need to multiply each element of 2 arrays and project a column which is a array and each element is the product result.

Example:

select * from vetor_query;

Returns:

query_id |pesos                                                                                               |
---------|----------------------------------------------------------------------------------------------------|
1        |{2.0000,0.4150,2.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000} |

And the query:

select * from vetor_documento;

Returns:

doc    |pesos                                                                                               |
-------|----------------------------------------------------------------------------------------------------|
d1.txt |{3.0000,0.8301,4.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000} |
d2.txt |{2.0000,0.0000,0.0000,0.0000,2.0000,2.0000,2.0000,2.0000,2.0000,0.0000,0.0000,0.0000,0.0000,0.0000} |
d3.txt |{0.0000,1.0729,0.0000,0.0000,0.0000,0.0000,2.0000,1.0000,0.0000,2.0000,2.0000,0.0000,0.0000,0.0000} |
d4.txt |{0.0000,1.0729,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,5.1699,4.0000,4.0000} |

I need to combine both queries(cross join) and produce as a result array of internal product for each doc and query_id.

My first attempt was this one:

select vq.query_id, vd.doc, unnest(vq.pesos) * unnest(vd.pesos)
from vetor_query vq
cross join vetor_documento vd;

However, it yields this error:

Functions and operators can take at most one set argument

4

1 回答 1

0

您可以使用该函数的便捷功能unnest()来并行取消嵌套多个数组。

LATERAL连接中执行此操作,将每个结果行相乘并将其提供给 ARRAY 构造函数:

SELECT q.query_id, d.doc, qd.prod
FROM   vetor_query          q
CROSS  JOIN vetor_documento d
CROSS  JOIN LATERAL (
   SELECT ARRAY(SELECT x*y FROM unnest(q.pesos, d.pesos) t(x, y)) AS prod
   ) qd;

这是假设所有数组都具有相同的长度,否则多余的元素用 NULL 填充。

有关的:

结果数组中的顺序对应于元素的原始顺序。但请考虑:

于 2017-06-05T04:06:47.177 回答