Repository navigation
Decision: merge scans of a table only where a not-null key pins them to one row #84
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
A basic graph pattern unfolds into one scan per triple pattern, joined on the shared variables. When several triple patterns read the same table, the SQL joins the table with itself:
?a ex:criticality "High" ; ex:hostname ?hisassets t0 JOIN assets t1 ON t1.id = t0.id, and two properties of one constant subject are aCROSS JOINof two key lookups. Ontop merges these scans on the primary key; in the benchmark of #69, PostgreSQL ran v12n's SQL 1.5–2.5× longer because of them (#28). The project plan calls for self-join elimination by primary and unique keys, only once differential tests are in place. The engine already reads unique keys per query for removing duplicates (Discussion #41).Decision
Which keys
INCLUDE, no table with inheritance children other than partitions).NOT NULL(a unique index admits several rows withNULL), the index compares with the column's own collation and the type's default operator class (as the plan's SQL=does), and the column type compares by=with no cast and no term key: integers,text/varchar/name,uuid,boolean,bytea,numeric,date,time,timestamp,timestamptz. Not floating point (-0 = 0, Discussion Decision: keep literal comparisons exact where SQL = is coarser, and lower-case language tags #65), notchar(n)(padding, Discussion Decision: keep literal comparisons exact where SQL = is coarser, and lower-case language tags #65), not types the engine compares as text.rr:sqlQueryviews have no keys and are never merged.Which scans
Two scans
tIandtJ(I < J) of the same table are merged whenOPTIONALpart (Discussion Decision: translate OPTIONAL to nested LEFT JOINs translated part by part #55), andkof one such key eithertI.k = tJ.k: anrr:joinConditionequality of the two columns, or a term comparison of the two plain columns (no base IRI, same datatype), which is how template decomposition joinsalert/{id}withalert/{id}; ortI.id = $1,tJ.id = $2with equal parameters), or the same column of a third scan (?f ex:onAsset ?a . ?a ex:hostname ?h ; ex:site ?scompares both scans ofassetswithalerts.asset_id).tJis then replaced bytIin the select list, every condition,FILTERandORDER BYvalue; the aliases after it shift down, as do the table ranges ofOPTIONALparts. The equalitiestI.k = tI.kon the key are dropped, repeated conditions are dropped, and the columns a solution fixes (#41) are those of both scans. Merging repeats until no pair is left.Why the result is the same
In every row the scope keeps, the conditions hold, so
tI.kandtJ.kare equal for every column of the key: directly, or because one comparison relation is transitive (SQL=within a btree operator family; term equality, which for the key types above holds exactly for equal values). The key is unique and not null, sotIandtJare the same table row. The combinations of rows the scope keeps are therefore exactly the combinations with one row in both scans, and replacingtJbytImaps them one to one onto the combinations the merged scope keeps: the same rows, each as many times. The dropped equalities compare aNOT NULLcolumn with itself and hold in every row; every other condition is kept, so noIS NOT NULLthat a dropped condition implied is lost. Inside anOPTIONALpart, the same holds for the rows the part adds to each left row, and where the part does not match, the merged scan's columns areNULLjust as both were.What is not merged
OPTIONAL(benchq04-optional:assets t0 LEFT JOIN assets t1 ON t1.id = t0.id AND t1.criticality IS NOT NULL).t1is the row oft0where the part matches andNULLwhere it does not, so replacingt1.cbyt0.cwould bind values where the part did not match. It would need each column oft1to becomeCASE WHEN <the part's conditions> THEN t0.c ENDeverywhere it is read, which the plan cannot express yet. Left for later; the SQL is unchanged.UNIONarms (Discussion Decision: translate UNION as a bag union of arms and give differently shaped terms their own columns #60): each arm is its ownSELECT; scans inside one arm are merged.Interactions
DISTINCTelision (Discussion Decision: count each triple once, keep bag semantics for solutions #41): a merged scan fixes the columns of both, and the set of tables is the same, so a plan whose keys proved no duplicates still does.ORDER BY(Discussion Decision: order solutions by SPARQL rules, with a fixed order where SPARQL leaves it open #63): sort keys read the merged scan; one plainSELECTstill sorts by the columns themselves.FILTER(Discussion Decision: encode FILTER errors as SQL NULL and compare by the SPARQL operator mapping #57): filters are rewritten, not moved; their scope is unchanged.v12n explainand the server's log of the unfolded SQL have no database and show the scans before merging, as they showDISTINCTwithout keys.DISTINCT, or with several branches), the catalog query now runs for it too; otherwise the number of statements is unchanged.Results
Differential tests: all 304 queries pass, the 282 of main unchanged and 22 in a new case
tests/diff/0010-self-joins(stars, constant subjects, a class of a second triples map over the table, stars on both sides of a join, a composite key, the parent of a referencing object map, non-key joins, a nullable unique column with twoNULLrows, a unique index over(grp, lower(name)), an alternate key,OPTIONALacross and inside,UNIONarms,DISTINCT,ORDER BY+LIMIT,FILTER). Database tests cover which keys qualify. Accepting nullable keys or expression indexes makes them fail (an extra solution with an unbound subject; two rows of one group merged).Benchmark (
bench/RESULTS.md, mean SQL execution per request frompg_stat_statements, main against the change on one machine): q02 4.75 → 1.50 ms at 100k (Ontop 1.69) and 32.0 → 18.4 ms at 1M (Ontop 24.6), 9.9 → 5.5 ms end to end at 100k; q03 0.86 → 0.34 ms (Ontop 0.34) and 9.5 → 4.3 ms (Ontop 4.6); q01 stays at 0.05 ms; q04 is unchanged by design.References
pg_index,pg_opclass— https://www.postgresql.org/docs/17/catalog-pg-index.html배경
기본 그래프 패턴은 트리플 패턴마다 스캔 하나로 펼쳐지고 공유 변수로 조인된다. 여러 트리플 패턴이 같은 테이블을 읽으면 SQL이 테이블을 자기 자신과 조인한다:
?a ex:criticality "High" ; ex:hostname ?h는assets t0 JOIN assets t1 ON t1.id = t0.id이고, 상수 주어의 속성 두 개는 키 조회 두 번의CROSS JOIN이다. Ontop은 기본 키로 이 스캔들을 합치며, #69 벤치마크에서 PostgreSQL은 이 때문에 v12n의 SQL을 1.5~2.5배 오래 실행했다(#28). 프로젝트 계획은 기본 키·고유 제약 기준 self-join 제거이고, 차등 테스트가 깔린 뒤에만 넣는다. 엔진은 이미 중복 제거를 위해 질의마다 고유 키를 읽는다(Discussion #41).결정
어떤 키
INCLUDE인덱스는 키 컬럼만, 파티션 외 상속 자식이 있는 테이블 제외)을 그대로 따른다.NOT NULL(고유 인덱스는NULL행을 여럿 허용), 인덱스가 컬럼 자신의 콜레이션과 타입의 기본 연산자 클래스로 비교(계획의 SQL=와 같음), 컬럼 타입이 캐스트·항 키 없이=로 비교됨: 정수,text/varchar/name,uuid,boolean,bytea,numeric,date,time,timestamp,timestamptz. 부동소수점(-0 = 0, Discussion Decision: keep literal comparisons exact where SQL = is coarser, and lower-case language tags #65),char(n)(패딩, Discussion Decision: keep literal comparisons exact where SQL = is coarser, and lower-case language tags #65), 텍스트로 비교하는 타입은 제외.rr:sqlQuery뷰는 키가 없어 합치지 않는다.어떤 스캔
같은 테이블의 두 스캔
tI와tJ(I < J)를 합치는 조건:OPTIONAL부분의 직속(Discussion Decision: translate OPTIONAL to nested LEFT JOINs translated part by part #55).k에 대해 다음 중 하나를 요구:tI.k = tJ.k: 두 컬럼의rr:joinCondition등식, 또는 두 일반 컬럼의 항 비교(기준 IRI 없음, 같은 데이터타입).alert/{id}끼리 템플릿 분해로 조인하는 경우다.tI.id = $1,tJ.id = $2, 매개변수 값이 같음), 또는 세 번째 스캔의 같은 컬럼(?f ex:onAsset ?a . ?a ex:hostname ?h ; ex:site ?s는assets의 두 스캔을 모두alerts.asset_id와 비교).그러면 select 목록, 모든 조건,
FILTER·ORDER BY값에서tJ를tI로 바꾸고, 그 뒤 별칭과OPTIONAL부분의 테이블 범위를 하나씩 당긴다. 키의tI.k = tI.k등식과 중복 조건을 버리고, 해가 고정하는 컬럼(#41)은 두 스캔의 것을 합친다. 합칠 쌍이 없을 때까지 반복한다.결과가 같은 이유
범위가 남기는 모든 행에서 조건이 성립하므로 키의 모든 컬럼에서
tI.k와tJ.k가 같다: 직접이거나, 하나의 비교 관계가 추이적이어서(btree 연산자 패밀리 안의 SQL=, 위 키 타입에서는 값이 같을 때만 성립하는 항 동일성). 키는 고유하고 NULL이 아니므로tI와tJ는 같은 테이블 행이다. 따라서 범위가 남기는 행 조합은 정확히 두 스캔에 같은 행이 있는 조합이고,tJ를tI로 바꾸면 합친 범위가 남기는 조합과 일대일로 대응한다: 같은 행을 같은 횟수만큼. 버리는 등식은NOT NULL컬럼을 자기와 비교하므로 모든 행에서 성립하고, 다른 조건은 모두 남으므로 버린 조건이 함의하던IS NOT NULL이 사라지지 않는다.OPTIONAL부분 안에서는 부분이 왼쪽 행마다 붙이는 행에 같은 논증이 성립하고, 부분이 맞지 않는 곳에서는 합친 스캔의 컬럼도 두 스캔처럼NULL이다.합치지 않는 것
OPTIONAL너머(벤치q04-optional:assets t0 LEFT JOIN assets t1 ON t1.id = t0.id AND t1.criticality IS NOT NULL).t1은 부분이 맞는 곳에서t0의 행이고 맞지 않는 곳에서NULL이므로,t1.c를t0.c로 바꾸면 부분이 맞지 않은 곳에서도 값이 묶인다. 읽는 곳마다t1의 각 컬럼을CASE WHEN <부분의 조건> THEN t0.c END로 바꿔야 하는데 지금 계획 구조로는 표현할 수 없다. 나중으로 미루며 SQL은 그대로다.UNION가지 사이(Discussion Decision: translate UNION as a bag union of arms and give differently shaped terms their own columns #60): 가지마다 별도SELECT다. 한 가지 안의 스캔은 합친다.상호작용
DISTINCT생략(Discussion Decision: count each triple once, keep bag semantics for solutions #41): 합친 스캔은 두 스캔의 컬럼을 모두 고정하고 테이블 집합은 같으므로, 키로 중복이 없다고 증명된 계획은 여전히 그렇다.ORDER BY(Discussion Decision: order solutions by SPARQL rules, with a fixed order where SPARQL leaves it open #63): 정렬 키가 합친 스캔을 읽고, 단일SELECT는 여전히 컬럼 자체로 정렬한다.FILTER(Discussion Decision: encode FILTER errors as SQL NULL and compare by the SPARQL operator mapping #57): 필터는 이름만 바뀌고 옮겨지지 않으며 범위도 그대로다.v12n explain**과 서버의 펼친 SQL 로그는 DB가 없어 합치기 전 스캔을 보여 준다. 키 없이DISTINCT를 보여 주는 것과 같다.DISTINCT아래, 또는 가지가 여럿)는 이제 카탈로그 질의가 그 테이블을 위해서도 돈다. 그 밖에는 문장 수가 그대로다.결과
차등 테스트: 304개 질의 모두 통과. main의 282개 그대로, 새 케이스
tests/diff/0010-self-joins22개(스타, 상수 주어, 같은 테이블의 두 번째 triples map 클래스, 조인 양쪽 스타, 복합 키, 참조 객체 맵의 부모, 키 아닌 조인,NULL두 행이 있는 NULL 허용 고유 컬럼,(grp, lower(name))고유 인덱스, 대체 키,OPTIONAL너머·안,UNION가지,DISTINCT,ORDER BY+LIMIT,FILTER). DB 테스트가 어떤 키가 해당하는지 확인한다. NULL 허용 키나 식 인덱스를 받아들이면 실패한다(주어가 unbound인 해가 더 나옴, 한 그룹의 두 행이 합쳐짐).벤치마크(
bench/RESULTS.md,pg_stat_statements의 요청당 평균 SQL 실행 시간, 같은 머신에서 main 대 변경): q02 10만 4.75 → 1.50 ms(Ontop 1.69), 100만 32.0 → 18.4 ms(Ontop 24.6), 10만 전체 9.9 → 5.5 ms. q03 0.86 → 0.34 ms(Ontop 0.34), 9.5 → 4.3 ms(Ontop 4.6). q01은 0.05 ms 그대로, q04는 설계상 변화 없음.참고
All reactions