Repository navigation
Decision: count each triple once, keep bag semantics for solutions #41
CharmingGroot
announced in
Announcements
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Background
An RDF graph is a set of triples. A triple produced by two duplicate rows of a logical table, by an R2RML view that repeats rows, or by two term maps (two predicate-object maps, two triples maps) is one triple, and a basic graph pattern matches it once. SPARQL then applies bag semantics to the solutions: a BGP has one solution per distinct mapping of its variables (SPARQL 1.1 §18.5), and projection keeps one solution per such mapping, so
SELECT ?city WHERE { ?p ex:city ?city }returns a city once per person.The engine returned one solution per SQL row instead. The W3C RDB2RDF expected outputs (
mapped*.nq) and Ontop count each triple once (#32, recorded as known mismatches in the differential tests since #23).Options considered:
FROM (SELECT DISTINCT ... FROM t) t0). Removes duplicate rows, but not the same triple from two term maps, because the branches for different term maps are combined withUNION ALL. It also adds one deduplication per scan instead of one per query.Decision
DISTINCT(one branch) orUNION(several term maps), and projects the selected variables in an outer query when some are not selected. UnderSELECT DISTINCTnothing changes.DISTINCTcolumns by first occurrence in the pattern, so the first subject comes first and an index on it can feedDISTINCTin order: the first rows then arrive without reading the whole table.pg_indexon each query (not cached, so a dropped key is never trusted). Only keys that always hold count: unique, valid, not deferrable, not partial, on plain columns; for an index withINCLUDE, only its key columns; none for a table with inheritance children (other than partitions), whose rows its indexes do not cover. When every table has a key among the columns that a solution fixes (those of terms whose term maps never render two values the same: columns, and injective templates), each solution fixes one row of every table, so the SQL keeps all rows withoutDISTINCT.UNIONcannot compare. Columns of variables that are not selected are compared as their type and text output (pg_typeof(c)::text || ' ' || c::text): equal type and text imply the same value, hence the same term.numericvalues of different scale, or the same string in avarcharand atextcolumn of two term maps for a variable that is not selected, still count twice.v12n explainhas no database and always shows theDISTINCT.Cost
Measured with
EXPLAIN ANALYZEon PostgreSQL 17 (testenv), a table of 1,000,000 rows (id,grp,name), and the same table with 10% duplicate rows, with and without an index onid. "first page" is the SQL as the engine runs it with the default row limit (LIMIT 10001pluscount(*) OVER ()), "all" without a limit. Best of three, in milliseconds.SELECT ?s ?n { ?s ex:name ?n }idSELECT ?n { ?s ex:name ?n }(?shidden)id?s ex:name ?n ; ex:grp ?g(self-join)id<…/r/42> ex:name ?nBefore the column order rule above, the hidden-
?squery took 1,122 ms for the first page (hash aggregate over every row); with it, 2.6 ms.So deduplication costs about 3-5x on full scans of keyless tables, and little on the first page when an index on the subject exists. Keyed tables, the common case, keep the old SQL at the price of one catalog query per execution. R2RML views (
rr:sqlQuery) have no keys and are always deduplicated. Merging self-joins on keys (#28) can reuse the same key metadata later.Results
Differential tests: 10 of the 15 W3C queries recorded under #32 now match Ontop; the other 5 now differ only in the
xsd:doublelexical form (#25). A new case,tests/diff/0003-duplicate-triples(duplicate rows, two predicate-object maps, two triples maps, an R2RML view, joins and projection), matches Ontop in all 8 queries; on the previous engine 6 of them differed.References
pg_index— https://www.postgresql.org/docs/17/catalog-pg-index.html배경
RDF 그래프는 트리플의 집합이다. logical table의 중복 행 두 개, 행을 반복하는 R2RML 뷰, 같은 트리플을 만드는 두 term map(predicate-object map 둘, 트리플 맵 둘)이 만든 트리플은 하나이고, 기본 그래프 패턴은 그것과 한 번 일치한다. SPARQL은 그다음 solution에 bag 의미를 적용한다. BGP는 변수 매핑이 서로 다를 때마다 solution을 하나씩 갖고(SPARQL 1.1 §18.5), 투영은 그 매핑마다 solution을 하나씩 남긴다. 그래서
SELECT ?city WHERE { ?p ex:city ?city }는 사람마다 도시를 하나씩 돌려준다.엔진은 대신 SQL 행마다 solution을 하나씩 돌려줬다. W3C RDB2RDF 기대 출력(
mapped*.nq)과 Ontop은 트리플마다 한 번 센다(#32, #23 이후 차등 테스트의 알려진 불일치).검토한 방법:
FROM (SELECT DISTINCT ... FROM t) t0). 중복 행은 없애지만, term map이 다른 가지를UNION ALL로 합치므로 두 term map이 만든 같은 트리플은 남는다. 중복 제거도 질의마다 한 번이 아니라 스캔마다 한 번이 된다.결정
DISTINCT(가지 하나)나UNION(term map 여러 개)으로 중복을 없앤 뒤, 고르지 않은 변수가 있으면 바깥 질의에서 고른 변수만 투영한다.SELECT DISTINCT는 그대로다.DISTINCT컬럼은 패턴에 처음 나오는 순서로 둔다. 첫 subject가 앞에 오므로 그 인덱스가 정렬된 순서로DISTINCT에 행을 넘길 수 있고, 첫 행이 테이블 전체를 읽기 전에 나온다.pg_index에서 테이블의 unique 키를 읽는다(캐시하지 않으므로 지워진 키를 믿지 않는다). 항상 성립하는 키만 센다: unique, valid, deferrable 아님, partial 아님, 식이 아닌 컬럼,INCLUDE가 있으면 키 컬럼만, 상속 자식 테이블이 있는 테이블(파티션 제외)은 인덱스가 자식 행을 덮지 않으므로 없음. 모든 테이블에서 solution이 고정하는 컬럼(서로 다른 값을 같은 문자열로 만들지 않는 term map의 컬럼: 컬럼, injective 템플릿) 안에 키가 있으면, solution 하나가 테이블마다 행 하나를 고정하므로 SQL은DISTINCT없이 모든 행을 그대로 둔다.UNION은 이를 비교하지 못한다. 투영하지 않는 변수의 컬럼은 타입과 text 출력으로 비교한다(pg_typeof(c)::text || ' ' || c::text). 타입과 text가 같으면 값이 같고, 따라서 term도 같다.numeric값, 투영하지 않는 변수에서 두 term map의varchar와text컬럼에 있는 같은 문자열은 여전히 두 번 센다.v12n explain은 DB가 없으므로 항상DISTINCT를 보여준다.비용
PostgreSQL 17(testenv)에서
EXPLAIN ANALYZE로 쟀다. 100만 행 테이블(id,grp,name)과, 같은 테이블에 중복 행 10%를 더한 것(id인덱스 있음/없음). "첫 페이지"는 엔진이 기본 행 상한으로 실행하는 SQL(LIMIT 10001과count(*) OVER ()), "전체"는 상한 없이. 세 번 중 최솟값, 밀리초.SELECT ?s ?n { ?s ex:name ?n }id인덱스SELECT ?n { ?s ex:name ?n }(?s숨김)id인덱스?s ex:name ?n ; ex:grp ?g(self-join)id인덱스<…/r/42> ex:name ?n위의 컬럼 순서 규칙을 넣기 전에는
?s를 숨긴 질의의 첫 페이지가 1,122ms(모든 행의 hash aggregate)였고, 넣은 뒤 2.6ms다.키 없는 테이블의 전체 스캔은 3~5배 느려지고, subject 인덱스가 있으면 첫 페이지 비용은 작다. 흔한 경우인 키 있는 테이블은 실행마다 catalog 질의 한 번으로 이전 SQL을 유지한다. R2RML 뷰(
rr:sqlQuery)는 키가 없어 항상 중복을 없앤다. 키로 self-join을 합치는 작업(#28)에서 같은 키 정보를 다시 쓸 수 있다.결과
차등 테스트: #32로 기록된 W3C 질의 15개 중 10개가 이제 Ontop과 같고, 나머지 5개는 이제
xsd:doublelexical form(#25)만 다르다. 새 케이스tests/diff/0003-duplicate-triples(중복 행, predicate-object map 둘, 트리플 맵 둘, R2RML 뷰, 조인과 투영)는 질의 8개 모두 Ontop과 같다. 이전 엔진에서는 6개가 달랐다.참고
pg_index— https://www.postgresql.org/docs/17/catalog-pg-index.htmlAll reactions