Skip to content

meilisearch/meilisearch-js

main
Switch branches/tags
Code

Latest commit

1279: build(deps-dev): bump @rollup/plugin-commonjs from 22.0.0 to 22.0.1 r=bidoubiwa a=dependabot[bot]

Bumps [`@rollup/plugin-commonjs](https://github.com/rollup/plugins/tree/HEAD/packages/commonjs)` from 22.0.0 to 22.0.1.
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a href="https://github.com/rollup/plugins/blob/master/packages/commonjs/CHANGELOG.md"><code>`@​rollup/plugin-commonjs</code>'s` changelog</a>.</em></p>
<blockquote>
<h2>v22.0.1</h2>
<p><em>2022-06-24</em></p>
<h3>Bugfixes</h3>
<ul>
<li>fix: Only proxy detected commonjs entry points (<a href="https://github.com/rollup/plugins/tree/HEAD/packages/commonjs/issues/1180">#1180</a>)</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a href="https://github.com/rollup/plugins/commit/59d8ac281d35bfbd57a369a1eecb820a0cf534d8"><code>59d8ac2</code></a> chore(release): commonjs v22.0.1</li>
<li><a href="https://github.com/rollup/plugins/commit/6ba714853b7c0cbe276980a202c4bd23b10c4763"><code>6ba7148</code></a> fix(commonjs): Only proxy detected commonjs entry points (<a href="https://github.com/rollup/plugins/tree/HEAD/packages/commonjs/issues/1180">#1180</a>)</li>
<li><a href="https://github.com/rollup/plugins/commit/3bc287cd6ad067a54e69ec17a1869cb12da2e952"><code>3bc287c</code></a> chore(release): commonjs v22.0.0</li>
<li>See full diff in <a href="https://github.com/rollup/plugins/commits/commonjs-v22.0.1/packages/commonjs">compare view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=`@rollup/plugin-commonjs&package-manager=npm_and_yarn&previous-version=22.0.0&new-version=22.0.1)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)`

You can trigger a rebase of this PR by commenting ``@dependabot` rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- ``@dependabot` rebase` will rebase this PR
- ``@dependabot` recreate` will recreate this PR, overwriting any edits that have been made to it
- ``@dependabot` merge` will merge this PR after your CI passes on it
- ``@dependabot` squash and merge` will squash and merge this PR after your CI passes on it
- ``@dependabot` cancel merge` will cancel a previously requested merge and block automerging
- ``@dependabot` reopen` will reopen this PR if it is closed
- ``@dependabot` close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
- ``@dependabot` ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
- ``@dependabot` ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
- ``@dependabot` ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)


</details>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
d67b006

Git stats

Files

Permalink
Failed to load latest commit information.
Type
Name
Latest commit message
Commit time
 
 
 
 
 
 
src
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Meilisearch-JavaScript

Meilisearch JavaScript

Meilisearch | Documentation | Slack | Roadmap | Website | FAQ

npm version Tests Prettier License Bors enabled

The Meilisearch API client written for JavaScript

Meilisearch JavaScript is the Meilisearch API client for JavaScript developers.

Meilisearch is an open-source search engine. Discover what Meilisearch is!

Table of Contents

📖 Documentation

See our Documentation or our API References.

🔧 Installation

We only guarantee that the package works with node >= 12 and node <= 16.

With npm:

npm install meilisearch

With yarn:

yarn add meilisearch

🏃‍♀️ Run Meilisearch

There are many easy ways to download and run a Meilisearch instance.

For example, using the curl command in your Terminal:

# Install Meilisearch
curl -L https://install.meilisearch.com | sh

# Launch Meilisearch
./meilisearch --master-key=masterKey

NB: you can also download Meilisearch from Homebrew or APT or even run it using Docker.

Import

Depending on the environment in which you are using Meilisearch, imports may differ.

Import Syntax

Usage in an ES module environment:

import { MeiliSearch } from 'meilisearch'

const client = new MeiliSearch({
  host: 'http://127.0.0.1:7700',
  apiKey: 'masterKey',
})

Include Script Tag

Usage in an HTML (or alike) file:

<script src='https://cdn.jsdelivr.net/npm/meilisearch@latest/dist/bundles/meilisearch.umd.js'></script>
<script>
  const client = new MeiliSearch({
    host: 'http://127.0.0.1:7700',
    apiKey: 'masterKey',
  })
</script>

Require Syntax

Usage in a back-end node environment

const { MeiliSearch } = require('meilisearch')

const client = new MeiliSearch({
  host: 'http://127.0.0.1:7700',
  apiKey: 'masterKey',
})

React Native

To make this package work with React Native, please add the react-native-url-polyfill.

Deno

Usage in a back-end deno environment

import { MeiliSearch } from "https://esm.sh/meilisearch"

const client = new MeiliSearch({
  host: 'http://127.0.0.1:7700',
  apiKey: 'masterKey',
})

🎬 Getting Started

Add Documents

const { MeiliSearch } = require('meilisearch')
// Or if you are in a ES environment
import { MeiliSearch } from 'meilisearch'

;(async () => {
  const client = new MeiliSearch({
    host: 'http://127.0.0.1:7700',
    apiKey: 'masterKey',
  })

  // An index is where the documents are stored.
  const index = client.index('movies')

  const documents = [
      { id: 1, title: 'Carol', genres: ['Romance', 'Drama'] },
      { id: 2, title: 'Wonder Woman', genres: ['Action', 'Adventure'] },
      { id: 3, title: 'Life of Pi', genres: ['Adventure', 'Drama'] },
      { id: 4, title: 'Mad Max: Fury Road', genres: ['Adventure', 'Science Fiction'] },
      { id: 5, title: 'Moana', genres: ['Fantasy', 'Action']},
      { id: 6, title: 'Philadelphia', genres: ['Drama'] },
  ]

  // If the index 'movies' does not exist, Meilisearch creates it when you first add the documents.
  let response = await index.addDocuments(documents)

  console.log(response) // => { "uid": 0 }
})()

With the uid, you can check the status (enqueued, processing, succeeded or failed) of your documents addition using the task.

Basic Search

// Meilisearch is typo-tolerant:
const search = await index.search('philoudelphia')
console.log(search)

Output:

{
  "hits": [
    {
      "id": "6",
      "title": "Philadelphia",
      "genres": ["Drama"]
    }
  ],
  "offset": 0,
  "limit": 20,
  "nbHits": 1,
  "processingTimeMs": 1,
  "query": "philoudelphia"
}

Custom Search

All the supported options are described in the search parameters section of the documentation.

await index.search(
  'wonder',
  {
    attributesToHighlight: ['*']
  }
)
{
  "hits": [
    {
      "id": 2,
      "title": "Wonder Woman",
      "genres": ["Action", "Adventure"],
      "_formatted": {
        "id": 2,
        "title": "<em>Wonder</em> Woman",
        "genres": ["Action", "Adventure"]
      }
    }
  ],
  "offset": 0,
  "limit": 20,
  "nbHits": 1,
  "processingTimeMs": 0,
  "query": "wonder"
}

Custom Search With Filters

If you want to enable filtering, you must add your attributes to the filterableAttributes index setting.

await index.updateAttributesForFaceting([
    'id',
    'genres'
  ])

You only need to perform this operation once.

Note that Meilisearch will rebuild your index whenever you update filterableAttributes. Depending on the size of your dataset, this might take time. You can track the process using the tasks).

Then, you can perform the search:

await index.search(
  'wonder',
  {
    filter: ['id > 1 AND genres = Action']
  }
)
{
  "hits": [
    {
      "id": 2,
      "title": "Wonder Woman",
      "genres": ["Action","Adventure"]
    }
  ],
  "offset": 0,
  "limit": 20,
  "nbHits": 1,
  "processingTimeMs": 0,
  "query": "wonder"
}

Placeholder Search

Placeholder search makes it possible to receive hits based on your parameters without having any query (q). To enable faceted search on your dataset you need to add genres in the settings.

await index.search(
  '',
  {
    filter: ['genres = fantasy'],
    facetsDistribution: ['genres']
  }
)
{
  "hits": [
    {
      "id": 2,
      "title": "Wonder Woman",
      "genres": ["Action","Adventure"]
    },
    {
      "id": 5,
      "title": "Moana",
      "genres": ["Fantasy","Action"]
    }
  ],
  "offset": 0,
  "limit": 20,
  "nbHits": 2,
  "processingTimeMs": 0,
  "query": "",
  "facetsDistribution": {
    "genres": {
      "Action": 2,
      "Fantasy": 1,
      "Adventure": 1
    }
  }
}

Abortable Search

You can abort a pending search request by providing an AbortSignal to the request.

const controller = new AbortController()

index
  .search('wonder', {}, {
    signal: controller.signal,
  })
  .then((response) => {
    /** ... */
  })
  .catch((e) => {
    /** Catch AbortError here. */
  })

controller.abort()

🤖 Compatibility with Meilisearch

This package only guarantees the compatibility with the version v0.27.0 of Meilisearch.

💡 Learn More

The following sections may interest you:

This repository also contains more examples.

⚙️ Development Workflow and Contributing

Any new contribution is more than welcome to this project!

If you want to know more about the development workflow or want to contribute, please visit our contributing guidelines for detailed instructions!

📜 API Resources

Search

client.index<T>('xxx').search(query: string, options: SearchParams = {}, config?: Partial<Request>): Promise<SearchResponse<T>>

client.index<T>('xxx').searchGet(query: string, options: SearchParams = {}, config?: Partial<Request>): Promise<SearchResponse<T>>

Documents

index.addDocuments(documents: Document<T>[]): Promise<EnqueuedTask>

index.addDocumentsInBatches(documents: Document<T>[], batchSize = 1000): Promise<EnqueuedTask[]>

index.updateDocuments(documents: Array<Document<Partial<T>>>): Promise<EnqueuedTask>

index.updateDocumentsInBatches(documents: Array<Document<Partial<T>>>, batchSize = 1000): Promise<EnqueuedTask[]>

index.getDocuments(params: getDocumentsParams): Promise<Document<T>[]>

index.getDocument(documentId: string): Promise<Document<T>>

index.deleteDocument(documentId: string | number): Promise<EnqueuedTask>

index.deleteDocuments(documentsIds: string[] | number[]): Promise<EnqueuedTask>

index.deleteAllDocuments(): Promise<Types.EnqueuedTask>

Tasks

Task list: client.getTasks(): Promise<Result<Task[]>>

One task: client.getTask(uid: number): Promise<Task>

Task list: index.getTasks(): Promise<Result<Task[]>>

One task: index.getTask(uid: number): Promise<Task>

  • Wait for one task:

Using de client: client.waitForTask(uid: number, { timeOutMs?: number, intervalMs?: number }): Promise<Task>

Using the index: index.waitForTask(uid: number, { timeOutMs?: number, intervalMs?: number }): Promise<Task>

  • Wait for multiple tasks:

Using the client: client.waitForTasks(uids: number[], { timeOutMs?: number, intervalMs?: number }): Promise<Result<Task[]>>

Using the index: index.waitForTasks(uids: number[], { timeOutMs?: number, intervalMs?: number }): Promise<Result<Task[]>>

Indexes

client.getIndexes(): Promise<Index[]>

client.getRawIndexes(): Promise<IndexResponse[]>

client.createIndex<T>(uid: string, options?: IndexOptions): Promise<EnqueuedTask>

  • Create a local reference to an index:

client.index<T>(uid: string): Index<T>

Using the client client.updateIndex(uid: string, options: IndexOptions): Promise<EnqueuedTask>

Using the index object: index.update(data: IndexOptions): Promise<EnqueuedTask>

Using the client client.deleteIndex(uid): Promise<void>

Using the index object: index.delete(): Promise<void>

index.getStats(): Promise<IndexStats>

  • Return Index instance with updated information:

index.fetchInfo(): Promise<Index>

  • Get Primary Key of an Index:

index.fetchPrimaryKey(): Promise<string | undefined>

Settings

index.getSettings(): Promise<Settings>

index.updateSettings(settings: Settings): Promise<EnqueuedTask>

index.resetSettings(): Promise<EnqueuedTask>

Synonyms

index.getSynonyms(): Promise<object>

index.updateSynonyms(synonyms: Synonyms): Promise<EnqueuedTask>

index.resetSynonyms(): Promise<EnqueuedTask>

Stop-words

Ranking rules

Distinct Attribute

Searchable Attributes

Displayed Attributes

Filterable Attributes

Sortable Attributes

Typo Tolerance

Keys

client.getKeys(): Promise<Result<Key[]>>

client.getKey(key: string): Promise<Key>

client.createKey(options: KeyPayload): Promise<Key>

client.updateKey(key: string, options: KeyPayload): Promise<Key>

client.deleteKey(key: string): Promise<void>

isHealthy

client.isHealthy(): Promise<boolean>

Health

client.health(): Promise<Health>

Stats

client.getStats(): Promise<Stats>

Version

client.getVersion(): Promise<Version>

Dumps

client.createDump(): Promise<Types.EnqueuedDump>

client.getDumpStatus(dumpUid: string): Promise<Types.EnqueuedDump>


Meilisearch provides and maintains many SDKs and Integration tools like this one. We want to provide everyone with an amazing search experience for any kind of project. If you want to contribute, make suggestions, or just know what's going on right now, visit us in the integration-guides repository.