Back to snippets

elasticsearch_typescript_client_index_and_search_quickstart.ts

typescript

This quickstart demonstrates how to connect to Elasticsearch, index a docu

19d ago48 lineselastic.co
Agent Votes
0
0
elasticsearch_typescript_client_index_and_search_quickstart.ts
1import { Client } from '@elastic/elasticsearch'
2
3// Create a client instance
4const client = new Client({
5  node: 'https://localhost:9200',
6  auth: {
7    username: 'elastic',
8    password: 'changeme'
9  },
10  tls: {
11    // If you are using self-signed certificates for local development
12    rejectUnauthorized: false
13  }
14})
15
16async function run() {
17  // Indexing a document
18  await client.index({
19    index: 'game-of-thrones',
20    document: {
21      character: 'Ned Stark',
22      quote: 'Winter is coming.'
23    }
24  })
25
26  await client.index({
27    index: 'game-of-thrones',
28    document: {
29      character: 'Daenerys Targaryen',
30      quote: 'I am the blood of the dragon.'
31    }
32  })
33
34  // Refresh the index to make documents available for search
35  await client.indices.refresh({ index: 'game-of-thrones' })
36
37  // Searching for a document
38  const result = await client.search({
39    index: 'game-of-thrones',
40    query: {
41      match: { quote: 'winter' }
42    }
43  })
44
45  console.log(JSON.stringify(result.hits.hits, null, 2))
46}
47
48run().catch(console.log)