Skip to content

Commit 30303e0

Browse files
committed
Add HackerNews dataset for vector search
1 parent 31048d2 commit 30303e0

File tree

1 file changed

+350
-0
lines changed

1 file changed

+350
-0
lines changed
Lines changed: 350 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,350 @@
1+
---
2+
description: 'Dataset containing 28+ million Hacker News postings & their vector embeddings
3+
sidebar_label: 'Hacker News Vector Search dataset'
4+
slug: /getting-started/example-datasets/hackernews-vector-search-dataset
5+
title: 'Hacker News Vector Search dataset'
6+
keywords: ['semantic search', 'vector similarity', 'approximate nearest neighbours', 'embeddings']
7+
---
8+
9+
## Introduction {#introduction}
10+
11+
The [Hacker News dataset](https://news.ycombinator.com/) contains 28.74 million
12+
postings and their vector embeddings. The embeddings were generated using [SentenceTransformers](https://sbert.net/) model [all-MiniLM-L6-v2](https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2). The dimension of each embedding vector is `384`.
13+
14+
This dataset can be used to walk through the design, sizing and performance aspects for a large scale,
15+
real world vector search application built on top of user generated, textual data.
16+
17+
## Dataset details {#dataset-details}
18+
19+
The complete dataset with vector embeddings is made available by ClickHouse as a single `Parquet` file in a `S3` bucket : https://clickhouse-datasets.s3.amazonaws.com/hackernews-miniLM/hackernews_part_1_of_1.parquet
20+
21+
We recommend users first run a sizing exercise to estimate the storage and memory requirements for this dataset by referring to the [documentation](../../engines/table-engines/mergetree-family/annindexes.md).
22+
23+
## Steps {#steps}
24+
25+
<VerticalStepper headerLevel="h3">
26+
27+
### Create table {#create-table}
28+
29+
Create the `hackernews` table to store the postings & their embeddings and associated attributes:
30+
31+
```sql
32+
CREATE TABLE hackernews
33+
(
34+
`id` Int32,
35+
`doc_id` Int32,
36+
`text` String,
37+
`vector` Array(Float32),
38+
`node_info` Tuple(
39+
start Nullable(UInt64),
40+
end Nullable(UInt64)),
41+
`metadata` String,
42+
`type` Enum8('story' = 1, 'comment' = 2, 'poll' = 3, 'pollopt' = 4, 'job' = 5),
43+
`by` LowCardinality(String),
44+
`time` DateTime,
45+
`title` String,
46+
`post_score` Int32,
47+
`dead` UInt8,
48+
`deleted` UInt8,
49+
`length` UInt32
50+
)
51+
ENGINE = MergeTree
52+
ORDER BY id;
53+
```
54+
55+
The `id` is just an incrementing integer. The additional attributes can be used in predicates to understand
56+
vector similarity search combined with post-filtering/pre-filtering as explained in the [documentation](../../engines/table-engines/mergetree-family/annindexes.md)
57+
58+
### Load data {#load-table}
59+
60+
To load the dataset from the `Parquet` file, run the following SQL statement:
61+
62+
```sql
63+
INSERT INTO hackernews SELECT * FROM s3('https://clickhouse-datasets.s3.amazonaws.com/hackernews-miniLM/hackernews_part_1_of_1.parquet');
64+
```
65+
66+
The loading of 28.74 million rows into the table will take a few minutes.
67+
```
68+
69+
### Build a vector similarity index {#build-vector-similarity-index}
70+
71+
Run the following SQL to define and build a vector similarity index on the `vector` column of the `hackernews` table :
72+
73+
```sql
74+
ALTER TABLE hackernews ADD INDEX vector_index vector TYPE vector_similarity('hnsw', 'cosineDistance', 768, 'bf16', 64, 512);
75+
76+
ALTER TABLE hackernews MATERIALIZE INDEX vector_index SETTINGS mutations_sync = 2;
77+
```
78+
79+
The parameters and performance considerations for index creation and search are described in the [documentation](../../engines/table-engines/mergetree-family/annindexes.md).
80+
The statement above uses values of 64 and 512 respectively for the HNSW hyperparameters `M` and `ef_construction`.
81+
Users need to carefully select optimal values for these parameters by evaluating index build time and search results quality
82+
corresponding to selected values.
83+
84+
Building and saving the index could even take a few minutes/hour for the full 28.74 million dataset, depending on the number of CPU cores available and the storage bandwidth.
85+
86+
### Perform ANN search {#perform-ann-search}
87+
88+
Once the vector similarity index has been built, vector search queries will automatically use the index:
89+
90+
```sql title="Query"
91+
SELECT id, title, text
92+
FROM hackernews
93+
ORDER BY cosineDistance( vector, <search vector>)
94+
LIMIT 10
95+
96+
```
97+
98+
The first time load of the vector index into memory could take a few seconds/minutes.
99+
100+
### Generate embeddings for search query {#generating-embeddings-for-search-query}
101+
102+
[Sentence Transformers](https://www.sbert.net/) provide local, easy to use embedding
103+
models for capturing the semantic meaning of sentences and paragraphs.
104+
105+
The dataset in this HackerNews dataset contains vector emebeddings generated from the
106+
[all-MiniLM-L6-v2](https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2) model.
107+
108+
An example Python script is provided below to demonstrate how to programmatically generate
109+
embedding vectors using `sentence_transformers1 Python package. The search embedding vector
110+
is then passed as an argument to the [`cosineDistance()`](/sql-reference/functions/distance-functions#cosineDistance) function in the `SELECT` query.
111+
112+
113+
```python
114+
from sentence_transformers import SentenceTransformer
115+
import sys
116+
117+
import clickhouse_connect
118+
119+
print("Initializing...")
120+
121+
model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
122+
123+
chclient = clickhouse_connect.get_client() # ClickHouse credentials here
124+
125+
while True:
126+
# Take the search query from user
127+
print("Enter a search query :")
128+
input_query = sys.stdin.readline();
129+
texts = [input_query]
130+
131+
# Run the model and obtain search vector
132+
print("Generating the embedding for ", input_query);
133+
embeddings = model.encode(texts)
134+
135+
print("Querying ClickHouse...")
136+
params = {'v1':list(embeddings[0]), 'v2':20}
137+
result = chclient.query("SELECT id, title, text FROM hackernews ORDER BY cosineDistance(vector, %(v1)s) LIMIT %(v2)s", parameters=params)
138+
print("Results :")
139+
for row in result.result_rows:
140+
print(row[0], row[2][:100])
141+
print("---------")
142+
143+
```
144+
145+
An example of running the above Python script and similarity search results are shown below
146+
(only 100 characters from each of the top 20 posts are printed):
147+
148+
```text
149+
Initializing...
150+
151+
Enter a search query :
152+
Are OLAP cubes useful
153+
154+
Generating the embedding for "Are OLAP cubes useful"
155+
156+
Querying ClickHouse...
157+
158+
Results :
159+
160+
27742647 smartmic:
161+
slt2021: OLAP Cube is not dead, as long as you use some form of:<p>1. GROUP BY multiple fi
162+
---------
163+
27744260 georgewfraser:A data mart is a logical organization of data to help humans understand the schema. Wh
164+
---------
165+
27761434 mwexler:&quot;We model data according to rigorous frameworks like Kimball or Inmon because we must r
166+
---------
167+
28401230 chotmat:
168+
erosenbe0: OLAP database is just a copy, replica, or archive of data with a schema designe
169+
---------
170+
22198879 Merick:+1 for Apache Kylin, it&#x27;s a great project and awesome open source community. If anyone i
171+
---------
172+
27741776 crazydoggers:I always felt the value of an OLAP cube was uncovering questions you may not know to as
173+
---------
174+
22189480 shadowsun7:
175+
_Codemonkeyism: After maintaining an OLAP cube system for some years, I&#x27;m not that
176+
---------
177+
27742029 smartmic:
178+
gengstrand: My first exposure to OLAP was on a team developing a front end to Essbase that
179+
---------
180+
22364133 irfansharif:
181+
simo7: I&#x27;m wondering how this technology could work for OLAP cubes.<p>An OLAP cube
182+
---------
183+
23292746 scoresmoke:When I was developing my pet project for Web analytics (<a href="https:&#x2F;&#x2F;github
184+
---------
185+
22198891 js8:It seems that the article makes a categorical error, arguing that OLAP cubes were replaced by co
186+
---------
187+
28421602 chotmat:
188+
7thaccount: Is there any advantage to OLAP cube over plain SQL (large historical database r
189+
---------
190+
22195444 shadowsun7:
191+
lkcubing: Thanks for sharing. Interesting write up.<p>While this article accurately capt
192+
---------
193+
22198040 lkcubing:Thanks for sharing. Interesting write up.<p>While this article accurately captures the issu
194+
---------
195+
3973185 stefanu:
196+
sgt: Interesting idea. Ofcourse, OLAP isn't just about the underlying cubes and dimensions,
197+
---------
198+
22190903 shadowsun7:
199+
js8: It seems that the article makes a categorical error, arguing that OLAP cubes were r
200+
---------
201+
28422241 sradman:OLAP Cubes have been disrupted by Column Stores. Unless you are interested in the history of
202+
---------
203+
28421480 chotmat:
204+
sradman: OLAP Cubes have been disrupted by Column Stores. Unless you are interested in the
205+
---------
206+
27742515 BadInformatics:
207+
quantified: OP posts with inverted condition: “OLAP != OLAP Cube” is the actual titl
208+
---------
209+
28422935 chotmat:
210+
rstuart4133: I remember hearing about OLAP cubes donkey&#x27;s years ago (probably not far
211+
---------
212+
```
213+
214+
## Summarization demo application {#summarization-demo-application}
215+
216+
The example above demonstrated semantic search and document retrieval using ClickHouse.
217+
218+
A very simple but high potential generative AI example application is presented next.
219+
220+
The application performs the following steps:
221+
222+
1. Accepts a _topic_ as input from the user
223+
2. Generates an embedding vector for the _topic_ by using `SentenceTransformers` with model `all-MiniLM-L6-v2`
224+
3. Retrieves highly relevant posts/comments using vector similarity search on the `hackernews` table
225+
4. Uses `LangChain` and OpenAI `gpt-3.5-turbo` Chat API to **summarize** the content retrieved in step #3.
226+
The posts/comments retrieved in step #3 are passed as _context_ to the Chat API and are the key link in Generative AI.
227+
228+
An example from running the summarization application is first listed below, followed by the code
229+
for the summarization application. Running the application requires an OpenAI API key to be set in the environment
230+
variable `OPENAI_API_KEY`. The OpenAI API key can be obtained after registering at https://platform.openai.com.
231+
232+
This application demonstrates a Generative AI use-case that is applicable to multiple enterprise domains like :
233+
customer sentiment analysis, technical support automation, mining user conversations, legal documents, medical records,
234+
meeting transcripts, financial statements, etc
235+
236+
```shell
237+
$ python3 summarize.py
238+
239+
Enter a search topic :
240+
ClickHouse performance experiences
241+
242+
Generating the embedding for ----> ClickHouse performance experiences
243+
244+
Querying ClickHouse to retrieve relevant articles...
245+
246+
Initializing chatgpt-3.5-turbo model...
247+
248+
Summarizing search results retrieved from ClickHouse...
249+
250+
Summary from chatgpt-3.5:
251+
The discussion focuses on comparing ClickHouse with various databases like TimescaleDB, Apache Spark,
252+
AWS Redshift, and QuestDB, highlighting ClickHouse's cost-efficient high performance and suitability
253+
for analytical applications. Users praise ClickHouse for its simplicity, speed, and resource efficiency
254+
in handling large-scale analytics workloads, although some challenges like DMLs and difficulty in backups
255+
are mentioned. ClickHouse is recognized for its real-time aggregate computation capabilities and solid
256+
engineering, with comparisons made to other databases like Druid and MemSQL. Overall, ClickHouse is seen
257+
as a powerful tool for real-time data processing, analytics, and handling large volumes of data
258+
efficiently, gaining popularity for its impressive performance and cost-effectiveness.
259+
```
260+
261+
Code for above application :
262+
263+
```python
264+
print("Initializing...")
265+
266+
import sys
267+
import json
268+
import time
269+
from sentence_transformers import SentenceTransformer
270+
271+
import clickhouse_connect
272+
273+
from langchain.docstore.document import Document
274+
from langchain.text_splitter import CharacterTextSplitter
275+
from langchain.chat_models import ChatOpenAI
276+
from langchain.prompts import PromptTemplate
277+
from langchain.chains.summarize import load_summarize_chain
278+
import textwrap
279+
import tiktoken
280+
281+
def num_tokens_from_string(string: str, encoding_name: str) -> int:
282+
encoding = tiktoken.encoding_for_model(encoding_name)
283+
num_tokens = len(encoding.encode(string))
284+
return num_tokens
285+
286+
model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
287+
288+
chclient = clickhouse_connect.get_client(compress=False) # ClickHouse credentials here
289+
290+
while True:
291+
# Take the search query from user
292+
print("Enter a search topic :")
293+
input_query = sys.stdin.readline();
294+
texts = [input_query]
295+
296+
# Run the model and obtain search or reference vector
297+
print("Generating the embedding for ----> ", input_query);
298+
embeddings = model.encode(texts)
299+
300+
print("Querying ClickHouse...")
301+
params = {'v1':list(embeddings[0]), 'v2':100}
302+
result = chclient.query("SELECT id,title,text FROM hackernews ORDER BY cosineDistance(vector, %(v1)s) LIMIT %(v2)s", parameters=params)
303+
304+
# Just join all the search results
305+
doc_results = ""
306+
for row in result.result_rows:
307+
doc_results = doc_results + "\n" + row[2]
308+
309+
print("Initializing chatgpt-3.5-turbo model")
310+
model_name = "gpt-3.5-turbo"
311+
312+
text_splitter = CharacterTextSplitter.from_tiktoken_encoder(
313+
model_name=model_name
314+
)
315+
316+
texts = text_splitter.split_text(doc_results)
317+
318+
docs = [Document(page_content=t) for t in texts]
319+
320+
llm = ChatOpenAI(temperature=0, model_name=model_name)
321+
322+
prompt_template = """
323+
Write a concise summary of the following in not more than 10 sentences:
324+
325+
326+
{text}
327+
328+
329+
CONSCISE SUMMARY :
330+
"""
331+
332+
prompt = PromptTemplate(template=prompt_template, input_variables=["text"])
333+
334+
num_tokens = num_tokens_from_string(doc_results, model_name)
335+
336+
gpt_35_turbo_max_tokens = 4096
337+
verbose = False
338+
339+
print("Summarizing search results retrieved from ClickHouse...")
340+
341+
if num_tokens <= gpt_35_turbo_max_tokens:
342+
chain = load_summarize_chain(llm, chain_type="stuff", prompt=prompt, verbose=verbose)
343+
else:
344+
chain = load_summarize_chain(llm, chain_type="map_reduce", map_prompt=prompt, combine_prompt=prompt, verbose=verbose)
345+
346+
summary = chain.run(docs)
347+
348+
print(f"Summary from chatgpt-3.5: {summary}")
349+
```
350+
</VerticalStepper>

0 commit comments

Comments
 (0)