@elastic/search-application-client

中文文档
8.9.0-2发布于 2024/01/29Apache-2.0TypeScriptESM + CJS近 30 天下载 4620

A Search Application Client for Elasticsearch

原始使用文档
文档目录17 节
  1. Quick Access
  2. Installation
  3. Using npm:
  4. Using yarn:
  5. In Browser via CDN
  6. Usage
  7. Importing the Client
  8. Creating an Instance of Client
  9. Using the Client
  10. API Reference
  11. SearchApplicationClient()
  12. QueryBuilder
  13. Advanced Usage
  14. Boilerplate template
  15. Using custom template
  16. Using dictionary for template
  17. Examples

Search Application Client

The Search Application Client is a JavaScript library that provides functionality for interacting with a search application in Elasticsearch.

ℹ️ The Search Application Client is in technical preview and is subject to change.

Quick Access

Here are some quick links to the important sections:

Installation

To install the Search Application Client, you can use npm or yarn.

Using npm:

npm install @elastic/search-application-client

Using yarn:

yarn add @elastic/search-application-client

In Browser via CDN

<script src="https://cdn.jsdelivr.net/npm/@elastic/search-application-client@latest"></script>

Usage

Importing the Client

You can import the Search Application Client in your JavaScript or TypeScript file using the following import statement:

import SearchApplicationClient from '@elastic/search-application-client';

Creating an Instance of Client

To use the Search Application Client, create an instance by calling the function returned by the imported module:

const client = SearchApplicationClient(applicationName, endpoint, apiKey, params);
  • applicationName: The name of the search application.
  • endpoint: The URL of the search application's endpoint.
  • apiKey: The API key for accessing the search application.
  • params (optional): Additional parameters to be passed to the client.
  • apiOptions (optional): Additional options to be passed to the API client.
    • cacheExpiration (optional): The cache expiration time in milliseconds. Default: 3600000 (one hour).
    • cache (optional): Enable/disables the cache. Default: true.
    • headers (optional): Additional headers to be passed to the API client.
  • Returns: A function that returns a new QueryBuilder instance.

Using the Client

The Search Application Client provides a QueryBuilder class that allows you to build complex search queries:

const results = await client()
  .query('John')
  .search()

The search method returns a Promise that resolves with the search results.

Use facets

To use facets filtering, specify facets in the client initialization:

const client = SearchApplicationClient('*search-application-name*', '*elasticsearch-endpoint*', '*apiKey*', {
  facets: {
    category: { type: 'terms', field: 'category.keyword', size: 10 },
    price: { type: 'stats', field: 'price', size: 10, disjunctive: true },
  },
});

const results = await client()
  .addFacetFilter('category', 'electronics')
  .addFacetFilter('price', { from: 100, to: 1000 })
  .addFacetFilter('author', 'orwell') // ❌ Throw an error, because the facet is not specified during initialization
  .setSort({'price': 'desc'})
  .search()

Use sorting

To use sorting, specify the field name and the sort order or pass _score to sort by relevance:

const results = await client()
  .setSort([{'publish_date': 'desc'}, "_score"])
  .search()

Use pagination

To use pagination, set the page number and the page size:

const results = await client()
  .setPageSize(20)
  .setFrom(20 * 2) // For the third page
  .search()

By default, page size is 10

Use additional parameters

const results = await client()
  .addParameter('custom-parameter', 'custom-value')
  .search()

API Reference

SearchApplicationClient()

Function to initialize searchApplicationClient and returns function to create an instance of the QueryBuilder.

  • applicationName (string): The name of the search application.
  • endpoint (string): The URL of the search application's endpoint.
  • apiKey (string): The API key for accessing the search application.
  • params? (Params): Additional parameters to be passed to the client.

Returns: function that returns new QueryBuilder instance.

QueryBuilder

This class provides methods for building search queries.

  • query(query: string): QueryBuilder Sets the search query. Returns: QueryBuilder instance.

  • addFacetFilter(field: string, value: FilterFieldValue): QueryBuilder Adds a facet filter to narrow down the search results. Returns: QueryBuilder instance.

    • field (string): The field name of the facet filter.
    • value (string | string[] | number | number[]): The value or range of values for the facet filter.
  • addParameter(field: string, value: unkown): QueryBuilder Adds a parameter to the query. Returns: QueryBuilder instance.

  • setPageSize(size: number): QueryBuilder Sets the size for maximum number of results to return. Returns: QueryBuilder instance.

  • setFrom(value: number): QueryBuilder Defines the number of results to skip, defaulting to 0. Returns: QueryBuilder instance.

  • setSort(sort: SortFields): QueryBuilder Sets the sorting criteria for the search results. Returns: QueryBuilder instance.

    • sort (Record<string, 'desc' | 'asc'> | '_score')[]): The sorting criteria for the search results.
  • search(): Promise<ResponseParams> Sends the search request to the search application. Use generic types for specify hits._source type. Returns: A promise that resolves to the search results.

    • hits: An array of search hits.
    • facets: An array of facet results.
    • aggregations: An object containing aggregation results.
    • total: The total number of search results.
    • took: The time taken for the search request.

Please refer to the code and type definitions for more details on the available methods and their parameters.

Advanced Usage

Boilerplate template

PUT _application/search_application/example-app
{
  "indices": ["example-index"],
  "template": {
    "script": {
      "lang": "mustache",
      "source": """
        {
          "query": {
            "bool": {
              "must": [
              {{#query}}
              {
                "query_string": {
                  "query": "{{query}}"
                }
              }
              {{/query}}
            ],
            "filter": {{#toJson}}_es_filters{{/toJson}}
            }
          },
          "aggs": {{#toJson}}_es_aggs{{/toJson}},
          "from": {{from}},
          "size": {{size}},
          "sort": {{#toJson}}_es_sort_fields{{/toJson}}
        }
      """,
      "params": {
        "query": "",
        "_es_filters": {},
        "_es_aggs": {},
        "_es_sort_fields": {},
        "size": 10,
        "from": 0
      }
    }
  }
}

Using custom template

To use custom template you can update boilerplate template within specific properties or params like highlight property:

PUT _application/search_application/example-app
{
  "indices": ["example-index"],
  "template": {
    "script": {
      "lang": "mustache",
      "source": """
        {
          "query": {
            "bool": {
              "must": [
              {{#query}}
                // ...
              {{/query}}
            ],
            "filter": {{#toJson}}_es_filters{{/toJson}}
            }
          },
          "_source": {
            "includes": ["title", "plot"]
          },
          "highlight": {
            "fields": {
              "title": { "fragment_size": 0 },
                "plot": { "fragment_size": 200 }
             }
          },
          "aggs": {{#toJson}}_es_aggs{{/toJson}},
          "from": {{from}},
          "size": {{size}},
          "sort": {{#toJson}}_es_sort_fields{{/toJson}}
        }
      """,
      "params": {
        "query": "",
        "_es_filters": {},
        "_es_aggs": {},
        "_es_sort_fields": {},
        "size": 10,
        "from": 0
      }
    }
  }
}

Using dictionary for template

To use template with typechecking you can update your template with prebuilded json schema by running command:

npx @elastic/search-application-client update-template

Once you have updated the template it will use the schema for typechecking of params for each request.

Examples

You can find usage examples in the examples/sandbox directory of this repository. These examples demonstrate how to use the search-application-client library.

版本与发布记录

@elastic/search-application-client 共发布 6 个版本,首次发布于 2023/07/04;过去 12 个月发布了 0 个版本。

版本发布日期距今
8.9.0-2latest2024/01/292 年前
8.9.0-12023/07/313 年前
8.9.02023/07/253 年前
8.9.0-alpha32023/07/043 年前
8.9.0-alpha22023/07/043 年前
8.9.0-alpha12023/07/043 年前

关于 @elastic/search-application-client 的常见问题

@elastic/search-application-client 是什么?

A Search Application Client for Elasticsearch

如何安装 @elastic/search-application-client?

在项目目录运行 npm install @elastic/search-application-client,或使用 pnpm add / yarn add / bun add。它还提供命令行工具 update-template,可以用 npx update-template 直接运行。

@elastic/search-application-client 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@elastic/search-application-client 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@elastic/search-application-client 可以商用吗?

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

@elastic/search-application-client 的下载量有多少?

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

@elastic/search-application-client 还在维护吗?

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