@elastic/app-search-node

中文文档
8.3.2发布于 2022/07/09Apache-2.0CommonJS近 30 天下载 2.3万

Elastic App Search Node.js client

原始使用文档
文档目录14 节
  1. Contents
  2. Getting started 🐣
  3. Versioning
  4. Usage
  5. Setup: Configuring the client and authentication
  6. API Methods
  7. For App Search APIs not available in this client
  8. Running tests
  9. FAQ 🔮
  10. Where do I report issues with the client?
  11. Where can I learn more about App Search?
  12. Where else can I go to get help?
  13. Contribute 🚀
  14. License 📗

⚠️ This client is deprecated ⚠️

As of Enterprise Search version 8.3.2, we are directing users to the new Enterprise Search Node Client and deprecating this client.

Our development effort on this project will be limited to bug fixes. All future enhancements will be focused on the Enterprise Search Node Client.

Thank you! - Elastic

Elastic App Search Logo

CircleCI build

A first-party Node.JS client for building excellent, relevant search experiences with Elastic App Search.

Contents


Getting started 🐣

To install this package, run:

npm install @elastic/app-search-node

Versioning

This client is versioned and released alongside App Search.

To guarantee compatibility, use the most recent version of this library within the major version of the corresponding App Search implementation.

For example, for App Search 7.3, use 7.3 of this library or above, but not 8.0.

If you are using the SaaS version available on swiftype.com of App Search, you should use the version 7.5.x of the client.

Usage

Setup: Configuring the client and authentication

Using this client assumes that you have already an instance of Elastic App Search up and running.

The client is configured using the baseUrlFn and apiKey parameters.

const apiKey = 'private-mu75psc5egt9ppzuycnc2mc3'
const baseUrlFn = () => 'http://localhost:3002/api/as/v1/'
const client = new AppSearchClient(undefined, apiKey, baseUrlFn)

Note:

The [apiKey] authenticates requests to the API. You can use any key type with the client, however each has a different scope. For more information on keys, check out the documentation.

Swiftype.com App Search users:

When using the SaaS version available on swiftype.com of App Search, you can configure the client using your hostIdentifier instead of the baseUrlFn parameter. The hostIdentifier can be found within the Credentials menu.

const AppSearchClient = require('@elastic/app-search-node')
const hostIdentifier = 'host-c5s2mj'
const apiKey = 'private-mu75psc5egt9ppzuycnc2mc3'
const client = new AppSearchClient(hostIdentifier, apiKey)

API Methods

Indexing: Creating or Replacing Documents
const engineName = 'favorite-videos'
const documents = [
  {
    id: 'INscMGmhmX4',
    url: 'https://www.youtube.com/watch?v=INscMGmhmX4',
    title: 'The Original Grumpy Cat',
    body: 'A wonderful video of a magnificent cat.'
  },
  {
    id: 'JNDFojsd02',
    url: 'https://www.youtube.com/watch?v=dQw4w9WgXcQ',
    title: 'Another Grumpy Cat',
    body: 'A great video of another cool cat.'
  }
]

client
  .indexDocuments(engineName, documents)
  .then(response => console.log(response))
  .catch(error => console.log(error))

Note that this API will not throw on an indexing error. Errors are inlined in the response body per document:

[
  { "id": "park_rocky-mountain", "errors": [] },
  {
    "id": "park_saguaro",
    "errors": ["Invalid field value: Value 'foo' cannot be parsed as a float"]
  }
]

Indexing: Updating Documents (Partial Updates)
const engineName = 'favorite-videos'
const documents = [
  {
    id: 'INscMGmhmX4',
    title: 'Updated title'
  }
]

client
  .updateDocuments(engineName, documents)
  .then(response => console.log(response))
  .catch(error => console.log(error))
Retrieving Documents
const engineName = 'favorite-videos'
const documentIds = ['INscMGmhmX4', 'JNDFojsd02']

client
  .getDocuments(engineName, documentIds)
  .then(response => console.log(response))
  .catch(error => console.log(error.errorMessages))
Listing Documents
const engineName = 'favorite-videos'

// Without paging
client
  .listDocuments(engineName)
  .then(response => console.log(response))
  .catch(error => console.log(error.errorMessages))

// With paging
client
  .listDocuments(engineName, { page: { size: 10, current: 1 } })
  .then(response => console.log(response))
  .catch(error => console.log(error.errorMessages))
Destroying Documents
const engineName = 'favorite-videos'
const documentIds = ['INscMGmhmX4', 'JNDFojsd02']

client
  .destroyDocuments(engineName, documentIds)
  .then(response => console.log(response))
  .catch(error => console.log(error.errorMessages))
Listing Engines
client
  .listEngines({ page: { size: 10, current: 1 } })
  .then(response => console.log(response))
  .catch(error => console.log(error.errorMessages))
Retrieving Engines
const engineName = 'favorite-videos'

client
  .getEngine(engineName)
  .then(response => console.log(response))
  .catch(error => console.log(error.errorMessages))
Creating Engines
const engineName = 'favorite-videos'

client
  .createEngine(engineName, { language: 'en' })
  .then(response => console.log(response))
  .catch(error => console.log(error.errorMessages))
Destroying Engines
const engineName = 'favorite-videos'

client
  .destroyEngine(engineName)
  .then(response => console.log(response))
  .catch(error => console.log(error.errorMessages))
Searching
const engineName = 'favorite-videos'
const query = 'cat'
const searchFields = { title: {} }
const resultFields = { title: { raw: {} } }
const options = { search_fields: searchFields, result_fields: resultFields }

client
  .search(engineName, query, options)
  .then(response => console.log(response))
  .catch(error => console.log(error.errorMessages))
const engineName = 'favorite-videos'
const searches = [
  { query: 'cat', options: {
      search_fields: { title: {} },
      result_fields: { title: { raw: {} } }
  } },
  { query: 'grumpy', options: {} }
]

client
  .multiSearch(engineName, searches)
  .then(response => console.log(response))
  .catch(error => console.log(error.errorMessages))
Query Suggestion
const engineName = 'favorite-videos'
const options = {
  size: 3,
  types: {
    documents: {
      fields: ['title']
    }
  }
}

client
  .querySuggestion(engineName, 'cat', options)
  .then(response => console.log(response))
  .catch(error => console.log(error.errorMessages))
Listing Curations
const engineName = 'favorite-videos'

client
  .listCurations(engineName)
  .then(response => console.log(response))
  .catch(error => console.log(error.errorMessages))

// Pagination details are optional
const paginationDetails = {
        page: {
          current: 2,
          size: 10
        }
      }

client
  .listCurations(engineName, paginationDetails)
  .then(response => console.log(response))
  .catch(error => console.log(error.errorMessages))
Retrieving Curations
const engineName = 'favorite-videos'
const curationId = 'cur-7438290'

client
  .getCuration(engineName, curationId)
  .then(response => console.log(response))
  .catch(error => console.log(error.errorMessages))
Creating Curations
const engineName = 'favorite-videos'
const newCuration = {
  queries: ['cat blop'],
  promoted: ['Jdas78932'],
  hidden: ['INscMGmhmX4', 'JNDFojsd02']
}

client
  .createCuration(engineName, newCuration)
  .then(response => console.log(response))
  .catch(error => console.log(error.errorMessages))
Updating Curations
const engineName = 'favorite-videos'
const curationId = 'cur-7438290'
// "queries" is required, either "promoted" or "hidden" is required.
// Values sent for all fields will overwrite existing values.
const newDetails = {
  queries: ['cat blop'],
  promoted: ['Jdas78932', 'JFayf782']
}

client
  .updateCuration(engineName, curationId, newDetails)
  .then(response => console.log(response))
  .catch(error => console.log(error.errorMessages))
Deleting Curations
const engineName = 'favorite-videos'
const curationId = 'cur-7438290'

client
  .destroyCuration(engineName, curationId)
  .then(response => console.log(response))
  .catch(error => console.log(error.errorMessages))
Retrieving Schemas
const engineName = 'favorite-videos'

client
  .getSchema(engineName)
  .then(response => console.log(response))
  .catch(error => console.log(error.errorMessages))
Updating Schemas
const engineName = 'favorite-videos'
const schema = {
  views: 'number',
  created_at: 'date'
}

client
  .updateSchema(engineName, schema)
  .then(response => console.log(response))
  .catch(error => console.log(error.errorMessages))
Create a Signed Search Key

Creating a search key that will only return the title field.

const publicSearchKey = 'search-xxxxxxxxxxxxxxxxxxxxxxxx'
// This name must match the name of the key above from your App Search dashboard
const publicSearchKeyName = 'search-key'
const enforcedOptions = {
  result_fields: { title: { raw: {} } },
  filters: { world_heritage_site: 'true' }
}

// Optional. See https://github.com/auth0/node-jsonwebtoken#usage for all options
const signOptions = {
  expiresIn: '5 minutes'
}

const signedSearchKey = AppSearchClient.createSignedSearchKey(
  publicSearchKey,
  publicSearchKeyName,
  enforcedOptions,
  signOptions
)

const baseUrlFn = () => 'http://localhost:3002/api/as/v1/'
const client = new AppSearchClient(undefined, signedSearchKey, baseUrlFn)

client.search('sample-engine', 'everglade')
Create a Meta Engine
const engineName = 'my-meta-engine'

client
  .createMetaEngine(engineName, ['source-engine-1', 'source-engine-2'])
  .then(response => console.log(response))
  .catch(error => console.log(error.errorMessages))
Add a Source Engine to a Meta Engine
const engineName = 'my-meta-engine'

client
  .addMetaEngineSources(engineName, ['source-engine-3'])
  .then(response => console.log(response))
  .catch(error => console.log(error.errorMessages))
Remove a Source Engine from a Meta Engine
const engineName = 'my-meta-engine'

client
  .deleteMetaEngineSources(engineName, ['source-engine-3'])
  .then(response => console.log(response))
  .catch(error => console.log(error.errorMessages))
Creating Engines
const engineName = 'my-meta-engine'

client
  .createEngine(engineName, {
    type: 'meta',
    source_engines: ['source-engine-1', 'source-engine-2']
  })
  .then(response => console.log(response))
  .catch(error => console.log(error.errorMessages))

For App Search APIs not available in this client

We try to keep this client up to date with all of the available API endpoints available from App Search.

There are a few APIs that may not be available yet. For those APIs, please use the low-level client to connect to hit any App Search endpoint.

const engineName = 'favorite-videos'
const options = {
  query: 'cats'
}

const Client = require('@elastic/app-search-node/lib/client')
const client = new Client('private-mu75psc5egt9ppzuycnc2mc3', 'http://localhost:3002/api/as/v1/')
client.post(`engines/${encodeURIComponent(engineName)}/search`, options).then(console.log)

Running tests

npm test

The specs in this project use node-replay to capture fixtures.

New fixtures should be captured from a running instance of App Search.

To capture new fixtures, run a command like the following:

nvm use
HOST_IDENTIFIER=host-c5s2mj API_KEY=private-b94wtaoaym2ovdk5dohj3hrz REPLAY=record npm run test -- -g 'should create a meta engine'

To break that down a little...

  • HOST_IDENTIFIER - Use this to override the fake value used in tests with an actual valid value for your App Search instance to record from
  • API_KEY - Use this to override the fake value used in tests with an actual valid value for your App Search instance to record from
  • REPLAY=record - Tells replay to record a new response if one doesn't already exist
  • npm run test - Run the tests
  • -- -g 'should create a meta engine' - Limit the tests to ONLY run the new test you've created, 'should create a meta engine' for example

This will create a new fixture, make sure you manually edit that fixture to replace the host identifier and api key recorded in that fixture with the values the tests use.

You'll also need to make sure that fixture is located in the correctly named directory under fixtures according to the host that was used.

You'll know if something is not right because this will error when you run npm run test with an error like:

Error: POST https://host-c5s2mj.api.swiftype.com:443/api/as/v1/engines refused: not recording and no network access

FAQ 🔮

Where do I report issues with the client?

If something is not working as expected, please open an issue.

Your best bet is to read the documentation.

Where else can I go to get help?

You can checkout the Elastic App Search community discuss forums.

Contribute 🚀

We welcome contributors to the project. Before you begin, a couple notes...

License 📗

Apache 2.0 © Elastic

Thank you to all the contributors!

版本与发布记录

@elastic/app-search-node 共发布 31 个版本,首次发布于 2019/07/30;过去 12 个月发布了 0 个版本。

版本发布日期距今
8.3.2latest2022/07/094 年前
8.2.02022/05/114 年前
8.1.02022/03/224 年前
8.0.02022/02/124 年前
7.17.02022/02/124 年前
7.16.1-beta.1next2022/01/144 年前

关于 @elastic/app-search-node 的常见问题

@elastic/app-search-node 是什么?

Elastic App Search Node.js client

如何安装 @elastic/app-search-node?

在项目目录运行 npm install @elastic/app-search-node,或使用 pnpm add / yarn add / bun add。

@elastic/app-search-node 支持 TypeScript 吗?

该包的 package.json 没有声明类型入口。需要类型提示时,可以在 npm 上查找社区维护的 @types/elastic__app-search-node 是否存在。

@elastic/app-search-node 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@elastic/app-search-node 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >= v6.5.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@elastic/app-search-node 可以商用吗?

@elastic/app-search-node 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@elastic/app-search-node 的下载量有多少?

根据 npm 官方下载统计,@elastic/app-search-node 在 2026/10/13 – 2026/11/11 这 30 天内被下载 22,952 次,日均约 765 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@elastic/app-search-node 还在维护吗?

最新版本 8.3.2 发布于 2022/07/09(4 年前);至今共发布 31 个版本,其中过去 12 个月发布了 0 个;首次发布于 2019/07/30。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。