STEP 7–8 거리로 찾는다Finding by Distance ← 발표자료Slides
DH2026 Workshop · 보조자료Supplement

검색은 거리를 재는 일이다Search Is Measuring Distance

RAG의 검색에는 마법이 없다. 질문을 좌표로 바꾸고, 자료의 좌표들과 거리를 재고, 가까운 순으로 줄 세운다. 그게 전부다. 여기서는 그 거리 계산을 1차원부터 차근차근 쌓아 올려, 384차원에서도 똑같은 산수라는 것을 실제 숫자로 확인한다.There is no magic in RAG retrieval. Turn the question into a coordinate, measure its distance to every coordinate in the corpus, and sort. That is all of it. Here we build that calculation up from one dimension, and confirm with real numbers that it is the same arithmetic at 384.
① STEP 7 · 질문도 좌표가 된다STEP 7 · The question becomes a coordinate

같은 자로 재야 비교할 수 있다You Must Measure With the Same Ruler

자료를 임베딩한 바로 그 인코더로 질문도 임베딩한다. 다른 자로 잰 길이를 비교할 수 없듯, 같은 모델을 써야 거리가 의미를 갖는다.The question goes through the very encoder that embedded the corpus. You cannot compare lengths measured with different rulers; only the same model makes the distance mean anything.

질문Question 384차원 · 메타데이터 없음 dims · no metadata
How many people still live in extreme poverty?
workshop_code.md7-1
qv = embeddings.embed_query(query)   # 청크와 같은 인코더same encoder as the chunks
[+0.0672, -0.0524, -0.0036, +0.0941, -0.0382, -0.0046, -0.0592, +0.0583, … ] — 총 384개 · 길이 1.0384 numbers · length 1.0
청크와 같은 점Same as a chunk

같은 인코더 · 같은 384차원Same encoder, same 384 dimensions

같은 좌표계 위에 놓인다. 그래야 사이의 거리를 잴 수 있다.It lands in the same coordinate system — which is what makes distance measurable.

다른 점Different

메타데이터가 없다No metadata

질문에는 Goal도 쪽수도 없다. 전거는 찾아낸 쪽에만 있다.A question has no Goal, no page range. Provenance belongs to what is found.

② 거리 · 1차원Distance · one dimension

거리는 “빼기”에서 시작한다Distance Begins With Subtraction

수직선 위의 두 점 사이 거리는 빼면 끝이다. 3과 7의 거리는 4. 점을 끌어서 움직여 보라.On a number line, the distance between two points is just a subtraction. From 3 to 7 is 4. Drag the dots.

빼면 음수가 나올 수 있다. 거리는 음수일 수 없으므로 부호를 없애야 한다 — 그래서 제곱한다.Subtraction can go negative. A distance cannot be negative, so the sign has to go — which is why we square it.
③ 거리 · 2차원Distance · two dimensions

축이 둘이면 — 피타고라스Two Axes — Pythagoras

가로로 3, 세로로 4 떨어져 있으면 직선 거리는 5다. 중학교에서 배운 그것이다. 가로차와 세로차를 각각 제곱해 더하고, 제곱근을 취한다. 두 점을 끌어 움직여 보라.Three across and four up gives five as the crow flies — the theorem everyone met at school. Square each difference, add them, take the square root. Drag the two points.

여기까지가 전부다. 축이 몇 개든 방법은 같다 — 축마다 차이를 구해 제곱하고, 전부 더하고, 제곱근을 취한다.That is the whole method. However many axes there are, it does not change — take each difference, square it, sum them all, take the root.
④ 거리 · 384차원Distance · 384 dimensions

축이 384개여도 똑같다It Is the Same With 384 Axes

그림은 못 그린다. 하지만 계산은 조금도 달라지지 않는다. 항이 2개에서 384개로 늘어날 뿐이다.You cannot draw it. But the calculation does not change at all — there are simply 384 terms instead of two.

d = √( (a0−b0)² + (a1−b1)² + … + (a383−b383)² )

실제로 해 보자. 질문 벡터와 1등으로 뽑힌 청크 G01-S01의 거리를 한 항씩 계산한다.Let us actually do it — the distance between the query and G01-S01, the nearest chunk, computed one term at a time.

0 / 384
⑤ 이유Why

왜 제곱하고, 왜 제곱근인가Why Square, and Why Take the Root

제곱하는 이유Why square

부호를 없애기 위해To get rid of the sign

차이는 음수일 수 있다. −0.14와 +0.14는 벌어진 정도가 같다. 제곱하면 둘 다 0.0196이 되어 부호가 사라진다. 덤으로 큰 차이가 더 크게 반영된다 — 조금 다른 것보다 많이 다른 것에 민감해진다.A difference can be negative, yet −0.14 and +0.14 are equally far apart. Squaring makes both 0.0196 and the sign disappears. As a bonus, large gaps count for more — the measure grows sensitive to the dimensions where the two really differ.

제곱근을 취하는 이유Why the root

원래 단위로 되돌리려고To return to the original unit

제곱해서 더한 값은 넓이 같은 단위가 되어 버린다. 제곱근을 취해야 다시 길이가 된다. 넓이 5인 정사각형의 한 변이 √5인 것과 같다.Once squared and summed, the number is in something like units of area. The square root brings it back to a length — just as a square of area 5 has sides of √5.

L2 거리 · 유클리드 거리L2 distance · Euclidean distance

이 방식을 L2 거리 또는 유클리드 거리라 부른다. 자로 재는 그 거리, 우리가 평소에 “거리”라고 부르는 바로 그것이다. 이름이 어려워 보일 뿐 새로운 개념이 아니다.This is called L2 distance, or Euclidean distance — the distance you get with a ruler, the one everybody already means by “distance”. The name is forbidding; the idea is not new.

⑥ 정렬Sorting

176개 전부와 재고, 줄 세운다Measure Against All 176, Then Sort

방금 한 계산을 176번 반복하면 검색이 끝난다. 가까운 순으로 정렬해 위에서 몇 개를 가져오면 그것이 검색 결과다.Repeat what we just did 176 times and the search is done. Sort by distance, take the top few — that is the result.

workshop_code.md8-1
distances = []
for v in V:                          # 청크 176개176 chunks
    diff = v - Q                       # 384개의 차이384 differences
    dist = np.sqrt((diff ** 2).sum())  # 제곱 → 합 → 제곱근square → sum → root
    distances.append(dist)

order = np.argsort(distances)          # 가까운 순으로nearest first
가장 가까움Nearest
0.7861
G01-S01
중앙값Median
1.2086
대부분 이 언저리where most of them sit
가장 멂Farthest
1.4104
주제가 전혀 다르다an entirely different topic
1등 0.7861과 꼴찌 1.4104의 차이는 크지 않아 보인다. 정규화된 벡터의 거리는 0에서 2 사이에 놓이기 때문이다 — 중요한 것은 절댓값이 아니라 순서다.The gap between first (0.7861) and last (1.4104) looks small. That is because distances between normalised vectors always fall between 0 and 2 — what matters is not the absolute value but the ordering.
⑦ 정리In sum

FAISS가 하는 일이 이것이다This Is What FAISS Does

STEP 6에서 만든 IndexFlatL2가 하는 계산이 방금 우리가 손으로 한 것과 완전히 같다. 이름의 L2가 바로 이 거리다. STEP 9에서 두 결과가 일치하는지 직접 확인한다.The IndexFlatL2 we built in STEP 6 performs exactly the calculation we just did by hand. The L2 in its name is this distance. In STEP 9 we check that the two agree.

검색은 마법이 아니다.
빼고, 제곱하고, 더하고, 제곱근을 취한 뒤, 줄 세우는 일이다.
Retrieval is not magic.
Subtract, square, sum, take the root, and sort.
다음은 STEP 9 — 손계산과 FAISS를 대조하고, 찾아낸 결과에 전거를 붙인다.Next is STEP 9 — compare the hand calculation with FAISS, and attach provenance to what was found.
DH2026 Workshop · Build a Working RAG in Half a Day
질의 벡터는 sentence-transformers/all-MiniLM-L6-v2로 실제 임베딩 · 청크 벡터는 Source/sdg_embeddings.jsonl의 실제 값The query was embedded with the real sentence-transformers/all-MiniLM-L6-v2 · Chunk vectors are the actual values in Source/sdg_embeddings.jsonl
← 발표자료로 돌아가기Back to the slides · STEP 6 · STEP 9–10