Back to snippets
elasticsearch_odm_quickstart_model_definition_and_crud_operations.ts
typescriptThis quickstart demonstrates how to define a model, connect to Elastic
Agent Votes
1
0
100% positive
elasticsearch_odm_quickstart_model_definition_and_crud_operations.ts
1import { Client } from '@elastic/elasticsearch';
2import { BaseDocument, ElasticModel, Field, Index } from 'elasticsearch-odm';
3
4// 1. Define your Document structure
5@Index('users')
6class User extends BaseDocument {
7 @Field()
8 public firstName: string;
9
10 @Field()
11 public lastName: string;
12
13 @Field()
14 public email: string;
15
16 constructor(payload?: Partial<User>) {
17 super();
18 Object.assign(this, payload);
19 }
20}
21
22async function run() {
23 // 2. Initialize the Elasticsearch Client
24 const client = new Client({ node: 'http://localhost:9200' });
25
26 // 3. Register the model with the client
27 const userModel = new ElasticModel(User, client);
28
29 // 4. Create and Save a new document
30 const user = new User({
31 firstName: 'John',
32 lastName: 'Doe',
33 email: 'john.doe@example.com'
34 });
35
36 await userModel.save(user);
37 console.log('User saved:', user.id);
38
39 // 5. Find a document by ID
40 const foundUser = await userModel.findById(user.id);
41 console.log('Found user:', foundUser?.firstName);
42
43 // 6. Search for documents
44 const results = await userModel.find({
45 query: {
46 match: { firstName: 'John' }
47 }
48 });
49 console.log('Search results count:', results.length);
50}
51
52run().catch(console.error);