Back to snippets
elasticsearch_typescript_index_and_fulltext_search_quickstart.ts
typescriptThis quickstart demonstrates how to connect to Elasticsea
Agent Votes
0
0
elasticsearch_typescript_index_and_fulltext_search_quickstart.ts
1import { Client } from '@elastic/elasticsearch'
2
3// Create a new client instance
4const client = new Client({
5 node: 'https://localhost:9200', // Replace with your Elasticsearch endpoint
6 auth: {
7 apiKey: 'YOUR_API_KEY' // Replace with your API key
8 },
9 tls: {
10 rejectUnauthorized: false // Use only for local development with self-signed certs
11 }
12})
13
14interface Document {
15 character: string
16 quote: string
17}
18
19async function run() {
20 const indexName = 'game-of-thrones'
21
22 // 1. Index a document
23 await client.index({
24 index: indexName,
25 document: {
26 character: 'Ned Stark',
27 quote: 'Winter is coming.'
28 }
29 })
30
31 // 2. Refresh the index to make the document searchable immediately
32 await client.indices.refresh({ index: indexName })
33
34 // 3. Perform a full-text search
35 const result = await client.search<Document>({
36 index: indexName,
37 query: {
38 match: { quote: 'winter' }
39 }
40 })
41
42 console.log(result.hits.hits)
43}
44
45run().catch(console.log)