Skip to content

Instantly share code, notes, and snippets.

@Leo3965
Created July 24, 2024 19:02
Show Gist options
  • Save Leo3965/9a1f2602fa4b34d1bf7bf571f83c8b8e to your computer and use it in GitHub Desktop.
Save Leo3965/9a1f2602fa4b34d1bf7bf571f83c8b8e to your computer and use it in GitHub Desktop.
Elastic Search com Typescript
import { Client } from "@elastic/elasticsearch";
import { SearchHit } from "@elastic/elasticsearch/lib/api/types";
const endpoint = "";
const id = "";
const apiKey = "";
const client = new Client({
cloud: { id: id },
auth: { apiKey: apiKey },
});
interface Document {
character: string;
quote: string;
}
async function createIndex() {
await client.indices.create({ index: "my_index" });
}
async function createDocument() {
await client.index({
index: "my_index",
id: "my_document_id",
document: {
foo: "foo",
bar: "bar",
},
});
}
async function gettingDocument() {
await client.get({
index: "my_index",
id: "my_document_id",
});
}
async function searchingDocument() {
await client.search({
query: {
match: {
foo: "foo",
},
},
});
}
async function updatingDocument() {
await client.update({
index: "my_index",
id: "my_document_id",
doc: {
foo: "bar",
new_field: "new value",
},
});
}
async function deletingDocument() {
await client.delete({
index: "my_index",
id: "my_document_id",
});
}
async function deletingIndex() {
await client.indices.delete({ index: "my_index" });
}
async function createIndexes() {
// Let's start by indexing some data
await client.index({
index: "game-of-thrones",
document: {
character: "Ned Stark",
quote: "Winter is coming.",
},
});
await client.index({
index: "game-of-thrones",
document: {
character: "Daenerys Targaryen",
quote: "I am the blood of the dragon.",
},
});
await client.index({
index: "game-of-thrones",
document: {
character: "Tyrion Lannister",
quote: "A mind needs books like a sword needs a whetstone.",
},
});
// here we are forcing an index refresh, otherwise we will not
// get any result in the consequent search
await client.indices.refresh({ index: "game-of-thrones" });
}
async function searchByQuote(quote: string) {
// Let's search!
const result = await client.search<Document>({
index: "game-of-thrones",
query: {
match: { quote: quote },
},
});
console.log(result.hits.hits);
}
async function search(
index: string,
match: Partial<Document>
): Promise<SearchHit<Document[]>[]> {
const result = await client.search<Document[]>({
index,
query: {
match,
},
});
return result.hits.hits;
}
async function findIndexes(): Promise<void> {
console.log(await client.indices.exists({ index: "my_index" }));
}
async function main(): Promise<void> {
// await findIndexes();
// await createIndexes();
await searchByQuote("of");
console.log("---- custom ----");
console.log(await search("game-of-thrones", { quote: "of" }));
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment