• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

graphql-compose/graphql-compose-elasticsearch: Hide Elastic Search REST API behi ...

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称(OpenSource Name):

graphql-compose/graphql-compose-elasticsearch

开源软件地址(OpenSource Url):

https://github.com/graphql-compose/graphql-compose-elasticsearch

开源编程语言(OpenSource Language):

TypeScript 89.9%

开源软件介绍(OpenSource Introduction):

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

screen shot 2017-03-07 at 22 26 17

API proxy: Getting several raw elastic metric in one request

screen shot 2017-03-07 at 22 34 01

Mapping: Relay Cursor Connection

screen shot 2017-03-22 at 19 34 09

Mapping: Generated GraphQL Types and Documentation

screen shot 2017-03-22 at 19 33 24

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




鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
pgutkowski/KGraphQL: Pure Kotlin GraphQL implementation发布时间:2022-06-12
下一篇:
graphcool-examples/react-graphql发布时间:2022-06-12
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap