graphql elasticsearch 集成试用

时间:2023-02-03 00:51:52

graphql 是很方便的api 查询语言,elasticsearch 可以方便的进行全文检索的应用开发
有一个方便的npm 包graphql-compose-elasticsearch 可以进行es 的查询

测试使用docker 运行,参考代码https://github.com/rongfengliang/graphql-elasticsearch-demo

环境准备

  • docker-compose 文件
version: "3"
services:
  es:
    image: elasticsearch:5.6.12
    ports:
    - 9200:9200
    volumes:
    - ./es-data:/usr/share/elasticsearch/data
  web:
    build: ./
    ports:
    - 9201:9201
  • nodejs 应用构建dockerfile
FROM node:10.7-alpine
WORKDIR /app
COPY . /app
RUN npm install -g yarn
RUN yarn 
ENTRYPOINT [ "yarn","start" ]

使用说明

主要还是进行schema 的定义以及resolver 编写,demo 包含一个user 索引字段的映射处理,参考schema.js

const demoUserMapping = {
  properties: {
    name: {
      type: 'text',
      fields: {
        keyword: {
          type: 'keyword',
        },
      },
    },

resovler

const schema = new GraphQLSchema({
  query: new GraphQLObjectType({
    name: 'Query',
    fields: {
      userSearch: UserEsTC.getResolver('search').getFieldConfig(),
      userSearchConnection: UserEsTC.getResolver('searchConnection').getFieldConfig(),
      elastic50: elasticApiFieldConfig({
        host: 'http://es:9200',
        apiVersion: '5.0',
        log: 'trace',
      }),
    },
  }),
});

demo 中包含一个数据初始化 seedData.js

测试

  • 启动
docker-compose up -d
  • 查询
query {
  userSearch{
    hits{
      _id
      _node
      _source {
        gender
        birthday
        createdAt
      }
      _version
    }
  }
}
  • 查询结果

graphql elasticsearch 集成试用
graphql elasticsearch 集成试用

参考资料

https://github.com/rongfengliang/graphql-elasticsearch-demo
https://www.npmjs.com/package/graphql-compose-elasticsearch
https://graphql-compose.github.io/