npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

elastic-orm

v0.7.0

Published

Elasticsearch object relational mapper.

Downloads

93

Readme

ElasticORM

Package version Package downloads Package types definitions Package types definitions Top language

ElasticORM is an ORM tool that can run in javascript and helps developers to define a mapping of entities in one place by using decorators.

Installation

Install package from npm.

npm i elastic-orm @elastic/elasticsearch

Usage

1. Entity Definition

import { EsEntity, EsProperty, EsId } from 'elastic-orm';

@EsEntity('elastic_index') // specify elastic index
export class MyEntity {
  @EsId()
  public id: string;

  @EsProperty('integer')
  public foo: number;

  @EsProperty({ type: 'keyword' })
  public bar: string;

  @EsProperty('boolean')
  public fingersCrossedForUkraine: boolean = true;

  @EsProperty('date')
  public createdAt: Date;
}

2. Client and Repository Configuration

import { EsRepository } from 'elastic-orm';
import { Client } from '@elastic/elasticsearch';

const repository = new EsRepository(
  MyEntity,
  new Client(/* client configuration */),
);

Client configuration is provided here https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/7.17/client-connecting.html

3. Create Mapping

You can easily create index from you entity definition by running:

import { FactoryProvider } from 'elastic-orm';

const schema =
  FactoryProvider.makeSchemaManager().generateIndexSchema(MyEntity);
await repository.createIndex(schema);

Storing and Loading

const myEntity = new MyEntity()
myEntity.foo = 99
myEntity.bar = 'hello elastic search'
myEntity.isTutorial = true
myEntity.createdAt = new Date()
const createdEntity = await repository.create(myEntity)
const {entities, raw} = await repository.find({
  query: {
    term: {
      foo: 99,
    },
  },
})
  • entities contain deserialized entities.
  • raw contains raw response from elastic.

Repository methods

Entity methods

  • create: creates entity
  • createMultiple: creates multiple entities
  • update: updates entity
  • updateMultiple: updates multiple entities
  • index: index entity
  • indexMultiple: index multiple entities
  • delete: deletes entity
  • deleteMultiple: deletes multiple entities
  • findOne: finds single entity by specified query
  • findOneOrFail: finds single entity or throw exception
  • find: finds entities by query
  • findById finds single entity by id

Indices/Mapping methods

  • createIndex: creates index
  • deleteIndex: delete index
  • updateMapping: update mapping

Additional methods

  • on: registers function on specific repository actions

Advanced Usage

Query

Native query interface

Repository requires specific elastic structure object by default. Thanks to typescript query can be written really easily with autosuggestion. It will hint also properties from defined entity.

autosuggestion

Query Builder

If you are more familiar with builders. Bodybuilder can be used easily.

  1. Install bodybuilder package.
npm i bodybuilder
  1. Builder usage
import * as bodybuilder from 'bodybuilder';

const body = bodybuilder().query('match', 'foo', 1).build();
const res = await repository.findOne(body);

Nested Entities

import { EsEntity, EsProperty, EsId } from 'elastic-orm';

@EsEntity('elastic_index')
export class MyEntity {
  @EsId()
  public id: string;

  @EsProperty('integer')
  public foo: number;

  @EsProperty({ type: 'nested', entity: MyNestedEntity })
  public nestedItem: MyNestedEntity;

  @EsProperty({ type: 'nested', entity: MyNestedEntity })
  public nestedItems: MyNestedEntity[];
}

export class MyNestedEntity {
  @EsProperty('keyword')
  public name: string;
}

// query for nested entities
const res = await repository.findOne({
  query: {
    nested: {
      path: 'nestedItem',
      query: {
        bool: {
          must: [{ match: { 'nestedItem.name': 'find this string' } }],
        },
      },
    },
  },
});

Generating Entity Identifier

Identifier is automatically generated. But if you want to control generation of ids, you can use this approach:

@EsEntity('elastic_index')
export class MyEntity {
  @EsId({
    generator: () => {
      // apply custom logic here
      return 'customGeneratedId';
    },
  })
  public id: string;
}

Additional Field Options

For additional property options use parameter additionalFieldOptions.

import { EsEntity, EsProperty, EsId } from 'elastic-orm';

@EsEntity('elastic_index')
export class MyEntity {
  @EsId()
  public id: string;

  @EsProperty('text', {
    additionalFieldOptions: {
      enabled: false,
      fields: {
        raw: {
          type: 'keyword',
        },
      },
    },
  })
  public foo: string;
}

Aliases and Settings

@EsEntity('elastic_index', {
  aliases: ['elastic_index_alias_read', 'elastic_index_alias_write'],
  settings: {
    number_of_replicas: 1,
    number_of_shards: 5,
    // and other settings definitions
  },
  mapping: {
    dynamic: 'strict',
  },
})
export class MyEntity{}

Update Mapping

import { FactoryProvider } from 'elastic-orm';

const mapping = FactoryProvider.makeSchemaManager().buildMapping(
  FactoryProvider.makeMetaLoader().getReflectMetaData(TestingNestedClass),
);
await repository.updateMapping(mapping);

Delete Index

await repository.deleteIndex();

Global Request Manipulation

Enhancing elastic search requests is sometimes useful in one place. To do so you can register custom function which will be executed before every request on elastic.

For example:

  1. Enable explain for non production environments
repository.on('beforeRequest', (action, esParams, args) => {
  if (process.env.NODE_ENV !== 'production') {
    esParams.explain = true;
  }
});
  1. In case of find method replace index for alias
repository.on('beforeRequest', (action, esParams, args) => {
  if (action === 'find') {
    esParams.index = 'elastic_index_alias_read';
  }
});