Thursday, August 18, 2016

Hexastores are easy

Did you know that you can make a Hexastore from a RDF triple in just one line of SQL? (This needs PostgreSQL 9.4 or better, because of the multi-array unnest)

CREATE OR REPLACE FUNCTION hexify(
    IN sub text,
    IN pred text,
    IN obj text)
  RETURNS TABLE(ord text, a text, b text, c text) AS
$$select A.t || B.t || C.t as ord, A.v, B.v, C.v from (select * from unnest(ARRAY[sub, pred, obj],ARRAY['s', 'p', 'o'])) as A(v, t) cross join (select * from unnest(ARRAY[sub, pred, obj],ARRAY['s', 'p', 'o'])) as B(v, t) cross join (select * from unnest(ARRAY[sub, pred, obj],ARRAY['s', 'p', 'o'])) as C(v, t) where a.v != b.v and a.v != c.v and b.v != c.v order by ord desc$$
  LANGUAGE sql IMMUTABLE STRICT
  COST 100
  ROWS 6;

SELECT * FROM hexify('subject','predicate','object');


Sometimes, PostgreSQL SQL is just awesome...

More on Hexastores here and here.

1 comment:

  1. You could use some SQL beautifier, it's hard to read.

    SELECT A.t || B.t || C.t AS ord,
    A.v,
    B.v,
    C.v
    FROM
    (SELECT *
    FROM unnest(ARRAY[sub, pred, obj],ARRAY['s', 'p', 'o'])) AS A(v, t)
    CROSS JOIN
    (SELECT *
    FROM unnest(ARRAY[sub, pred, obj],ARRAY['s', 'p', 'o'])) AS B(v, t)
    CROSS JOIN
    (SELECT *
    FROM unnest(ARRAY[sub, pred, obj],ARRAY['s', 'p', 'o'])) AS C(v, t)
    WHERE a.v != b.v
    AND a.v != c.v
    AND b.v != c.v
    ORDER BY ord DESC

    ReplyDelete