arn-ob / meilisearch-js

Javascript client for the MeiliSearch API

Home Page:https://github.com/meilisearch/MeiliSearch

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

MeiliSearch-JavaScript

MeiliSearch JavaScript

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) // => { "updateId": 0 }
})()

With the updateId, you can check the status (enqueued, processing, processed or failed) of your documents addition using the update endpoint.

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 update status.

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

Indexes

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

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

  • Create a local reference to an index:

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

client.getOrCreateIndex<T>(uid: string, options?: IndexOptions): Promise<Index<T>>

client.updateIndex(uid: string, options: IndexOptions): Promise<Index> Or using the index object: index.update(data: IndexOptions): Promise<Index>

client.deleteIndex(uid): Promise<void> Or 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>

Updates

index.getUpdateStatus(updateId: number): Promise<Update>

index.getAllUpdateStatus(): Promise<Update[]>

  • Wait for pending update:

index.waitForPendingUpdate(updateId: number, { timeOutMs?: number, intervalMs?: number }): Promise<Update>

Documents

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

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

index.updateDocuments(documents: Document<T>[]): Promise<EnqueuedUpdate>

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

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

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

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

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

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

Settings

index.getSettings(): Promise<Settings>

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

index.resetSettings(): Promise<EnqueuedUpdate>

Synonyms

index.getSynonyms(): Promise<object>

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

index.resetSynonyms(): Promise<EnqueuedUpdate>

Stop-words

Ranking rules

Distinct Attribute

Searchable Attributes

Displayed Attributes

Filterable Attributes

Sortable Attributes

Keys

client.getKeys(): Promise<Keys>

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.

About

Javascript client for the MeiliSearch API

https://github.com/meilisearch/MeiliSearch

License:MIT License


Languages

Language:TypeScript 95.2%Language:JavaScript 4.1%Language:CSS 0.3%Language:HTML 0.2%Language:Shell 0.2%