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

graphql-compose-elasticsearch

v5.2.3

Published

Elastic search via GraphQL

Downloads

6,184

Readme

graphql-compose-elasticsearch

npm trends Commitizen friendly semantic-release

This module expose Elastic Search REST API via GraphQL.

Elastic Search REST API proxy

Supported all elastic versions that support official elasticsearch-js client. Internally it parses its source code annotations and generates all available methods with params and descriptions to GraphQL Field Config Map. You may put this config map to any GraphQL Schema.

import { GraphQLSchema, GraphQLObjectType } from 'graphql';
import elasticsearch from 'elasticsearch';
import { elasticApiFieldConfig } from 'graphql-compose-elasticsearch';

const schema = new GraphQLSchema({
  query: new GraphQLObjectType({
    name: 'Query',
    fields: {
      elastic50: elasticApiFieldConfig(
        // you may provide existed Elastic Client instance
        new elasticsearch.Client({
          host: 'http://localhost:9200',
          apiVersion: '5.0',
        })
      ),

      // or may provide just config
      elastic24: elasticApiFieldConfig({
        host: 'http://user:pass@localhost:9200',
        apiVersion: '2.4',
      }),

      elastic17: elasticApiFieldConfig({
        host: 'http://user:pass@localhost:9200',
        apiVersion: '1.7',
      }),
    },
  }),
});

Full code example

Live demo of Introspection of Elasticsearch API via Graphiql


ObjectTypeComposer from Elastic mapping

In other side this module is a plugin for graphql-compose, which derives GraphQLType from your elastic mapping generates tons of types, provides all available methods in QueryDSL, Aggregations, Sorting with field autocompletion according to types in your mapping (like Dev Tools Console in Kibana).

Generated ObjectTypeComposer model has several awesome resolvers:

  • search - greatly simplified elastic search method. According to GraphQL adaptation and its projection bunch of params setup automatically due your graphql query (eg _source, explain, version, trackScores), other rare fine tuning params moved to opts input field.
  • searchConnection - elastic search method that implements Relay Cursor Connection spec for infinite lists. Internally it uses cheap search_after API. One downside, Elastic does not support backward scrolling, so before argument will not work.
  • searchPagination - elastic search method that has page and perPage arguments
  • findById - get elastic record by id
  • updateById - update elastic record by id
  • feel free to add your resolver or ask for a new one
import { GraphQLSchema, GraphQLObjectType } from 'graphql';
import elasticsearch from 'elasticsearch';
import { composeWithElastic } from 'graphql-compose-elasticsearch';

const mapping = {
  properties: {
    name: {
      type: 'text',
      fields: {
        keyword: {
          type: 'keyword',
        },
      },
    },
    gender: {
      type: 'keyword',
    },
    skills: {
      type: 'text',
    },
    languages: {
      type: 'keyword',
    },
    location: {
      properties: {
        name: {
          type: 'text',
        },
        point: {
          type: 'geo_point',
        },
      },
    },
    createdAt: {
      type: 'date',
    },
  },
};

const UserTC = composeWithElastic({
  graphqlTypeName: 'UserES',
  elasticIndex: 'user',
  elasticType: 'user',
  elasticMapping: mapping,
  elasticClient: new elasticsearch.Client({
    host: 'http://localhost:9200',
    apiVersion: '5.0',
    log: 'trace',
  }),
  // elastic mapping does not contain information about is fields are arrays or not
  // so provide this information explicitly for obtaining correct types in GraphQL
  pluralFields: ['skills', 'languages'],
});

const Schema = new GraphQLSchema({
  query: new GraphQLObjectType({
    name: 'Query',
    fields: {
      user: UserTC.getResolver('search').getFieldConfig(),
      userPagination: UserTC.getResolver('searchPagination').getFieldConfig(),
      userConnection: UserTC.getResolver('searchConnection').getFieldConfig(),
    },
  }),
});

Full code example

Installation

yarn add graphql graphql-compose elasticsearch graphql-compose-elasticsearch
// or
npm install graphql graphql-compose elasticsearch graphql-compose-elasticsearch --save

Modules graphql, graphql-compose, elasticsearch are in peerDependencies, so should be installed explicitly in your app.

Screenshots

API proxy: Raw search method

API proxy: Getting several raw elastic metric in one request

Mapping: Relay Cursor Connection

Mapping: Generated GraphQL Types and Documentation

FAQ

Creating custom Resolvers

If you need create something special, you may create a custom Resolver. For example, if you need to add a new tag for existing record, do it in the following manner (see full test-case):

ActivitiesEsTC.addResolver({
  name: 'addTag',
  kind: 'mutation',
  type: 'JSON',
  args: {
    id: 'String!',
    tag: 'String!',
  },
  resolve: ({ args }) => {
    return elasticClient.update({
      index: elasticIndex,
      type: elasticType,
      id: args.id,
      body: {
        script: {
          inline: 'ctx._source.tags.add(params.tag)',
          params: { tag: args.tag },
        },
      },
    });
  },
});

License

MIT