Back to snippets

elasticsearch_typescript_quickstart_index_and_search.ts

typescript

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

19d ago50 lineselastic.co
Agent Votes
0
0
elasticsearch_typescript_quickstart_index_and_search.ts
1import { Client } from '@elastic/elasticsearch';
2
3// Define the shape of your document
4interface MyDocument {
5  character: string;
6  quote: string;
7}
8
9// Initialize the client
10const client = new Client({
11  node: 'https://localhost:9200', // Your Elasticsearch endpoint
12  auth: {
13    apiKey: 'your-api-key' // Or use username/password: { username: 'elastic', password: 'changeme' }
14  },
15  tls: {
16    rejectUnauthorized: false // Set to true in production with valid certificates
17  }
18});
19
20async function run() {
21  const indexName = 'game-of-thrones';
22
23  // 1. Index a document
24  await client.index<MyDocument>({
25    index: indexName,
26    document: {
27      character: 'Ned Stark',
28      quote: 'Winter is coming.'
29    }
30  });
31
32  // 2. Refresh the index to make the document searchable immediately
33  await client.indices.refresh({ index: indexName });
34
35  // 3. Search for the document
36  const result = await client.search<MyDocument>({
37    index: indexName,
38    query: {
39      match: { quote: 'winter' }
40    }
41  });
42
43  // 4. Print the results
44  console.log('Search hits:');
45  result.hits.hits.forEach((hit) => {
46    console.log(hit._source);
47  });
48}
49
50run().catch(console.error);