graphql elasticsearch 集成試用

graphql 是很方便的api 查詢語言,elasticsearch 能夠方便的進行全文檢索的應用開發
有一個方便的npm 包graphql-compose-elasticsearch 能夠進行es 的查詢node

測試使用docker 運行,參考代碼https://github.com/rongfengliang/graphql-elasticsearch-demogit

環境準備

  • 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.jsgithub

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

resovlerweb

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.jsdocker

測試

  • 啓動
docker-compose up -d
  • 查詢
query {
  userSearch{
    hits{
      _id
      _node
      _source {
        gender
        birthday
        createdAt
      }
      _version
    }
  }
}
  • 查詢結果


參考資料

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

相關文章
相關標籤/搜索