GitHub - meilisearch/meilisearch-js: Javascript client for the MeiliSearch API
source link: https://github.com/meilisearch/meilisearch-js
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
MeiliSearch JavaScript
MeiliSearch | Documentation | Roadmap | Website | Blog | Twitter | FAQ
The MeiliSearch API client written for JavaScript
MeiliSearch JavaScript is the MeiliSearch API client for JavaScript developers. MeiliSearch is a powerful, fast, open-source, easy to use and deploy search engine. Both searching and indexing are highly customizable. Features such as typo-tolerance, filters, and synonyms are provided out-of-the-box.
Table of Contents
Documentation
See our Documentation or our API References.
Installation
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, if you use Docker:
$ docker pull getmeili/meilisearch:latest # Fetch the latest version of MeiliSearch image from Docker Hub $ docker run -it --rm -p 7700:7700 getmeili/meilisearch:latest ./meilisearch --master-key=masterKey
NB: you can also download MeiliSearch from Homebrew or APT.
Import
Front End or ESmodule
import MeiliSearch from 'meilisearch' const client = new MeiliSearch({ host: 'http://127.0.0.1:7700', apiKey: 'masterKey', })
HTML Import
<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', }) client.listIndexes().then(res => { console.log({ res }); }) </script>
Back-End CommonJs
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.
Getting Started
Add Documents
const MeiliSearch = require('meilisearch') // Or if you are on a front-end environment: import MeiliSearch from 'meilisearch' ;(async () => { const client = new MeiliSearch({ host: 'http://127.0.0.1:7700', apiKey: 'masterKey', }) const index = await client.createIndex('books') // If your index does not exist // OR const index = client.getIndex('books') // If your index exists const documents = [ { book_id: 123, title: 'Pride and Prejudice' }, { book_id: 456, title: 'Le Petit Prince' }, { book_id: 1, title: 'Alice In Wonderland' }, { book_id: 1344, title: 'The Hobbit' }, { book_id: 4, title: 'Harry Potter and the Half-Blood Prince', genre: 'fantasy' }, { book_id: 42, title: "The Hitchhiker's Guide to the Galaxy", genre: 'fantasy' } ] let response = await index.addDocuments(documents) console.log(response) // => { "updateId": 0 } })()
With the updateId
, you can check the status (enqueued
, processed
or failed
) of your documents addition using the update endpoint.
Basic Search
// MeiliSearch is typo-tolerant: const search = await index.search('harry pottre') console.log(search)
Output:
{ "hits": [ { "book_id": 4, "title": "Harry Potter and the Half-Blood Prince" } ], "offset": 0, "limit": 20, "nbHits": 1, "exhaustiveNbHits": false, "processingTimeMs": 1, "query": "harry pottre" }
Custom Search
All the supported options are described in the search parameters section of the documentation.
await index.search( 'prince', { attributesToHighlight: ['*'], filters: 'book_id > 10' } )
{ "hits": [ { "book_id": 456, "title": "Le Petit Prince", "_formatted": { "book_id": 456, "title": "Le Petit <em>Prince</em>" } } ], "offset": 0, "limit": 20, "nbHits": 1, "exhaustiveNbHits": false, "processingTimeMs": 0, "query": "prince" }
Placeholder Search
Placeholder search makes it possible to receive hits based on your parameters without having any query (q
).
await index.search( '', { facetFilters: ['genre:fantasy'], facetsDistribution: ['genre'] } )
{ "hits": [ { "id": 4, "title": "Harry Potter and the Half-Blood Prince", "genre": "fantasy" }, { "id": 42, "title": "The Hitchhiker's Guide to the Galaxy", "genre": "fantasy" } ], "offset": 0, "limit": 20, "nbHits": 2, "exhaustiveNbHits": false, "processingTimeMs": 0, "query": "", "facetsDistribution": { "genre": { "fantasy": 2 } }, "exhaustiveFacetsCount": true }
Abortable Search
You can abort a pending search request by providing an AbortSignal to the request.
const controller = new AbortController() index .search('prince', {}, 'POST', { 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.17.0 of MeiliSearch.
Learn More
The following sections may interest you:
- Manipulate documents: see the API references or read more about documents.
- Search: see the API references or follow our guide on search parameters.
- Manage the indexes: see the API references or read more about indexes.
- Configure the index settings: see the API references or follow our guide on settings parameters.
This repository also contains more examples.
Development Workflow and Contributing
Any new contribution is more than welcome in 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
- Make a search request:
client.getIndex<T>('xxx').search(query: string, options: SearchParams = {}, method: 'POST' | 'GET' = 'POST', config?: Partial<Request>): Promise<SearchResponse<T>>
Indexes
- List all indexes:
client.listIndexes(): Promise<IndexResponse[]>
- Create new index:
client.createIndex<T>(uid: string, options?: IndexOptions): Promise<Index<T>>
- Get index object:
client.getIndex<T>(uid: string): Index<T>
- Get or create index if it does not exist
client.getOrCreateIndex<T>(uid: string, options?: IndexOptions): Promise<Index<T>>
- Show Index information:
index.show(): Promise<IndexResponse>
- Update Index:
index.updateIndex(data: IndexOptions): Promise<IndexResponse>
- Delete Index:
index.deleteIndex(): Promise<void>
- Get specific index stats
index.getStats(): Promise<IndexStats>
Updates
- Get One update info:
index.getUpdateStatus(updateId: number): Promise<Update>
- Get all updates info:
index.getAllUpdateStatus(): Promise<Update[]>
- Wait for pending update:
index.waitForPendingUpdate(updateId: number, { timeOutMs?: number, intervalMs?: number }): Promise<Update>
Documents
- Add or replace multiple documents:
index.addDocuments(documents: Document<T>[]): Promise<EnqueuedUpdate>
- Add or update multiple documents:
index.updateDocuments(documents: Document<T>[]): Promise<EnqueuedUpdate>
- Get Documents:
index.getDocuments(params: getDocumentsParams): Promise<Document<T>[]>
- Get one document:
index.getDocument(documentId: string): Promise<Document<T>>
- Delete one document:
index.deleteDocument(documentId: string | number): Promise<EnqueuedUpdate>
- Delete multiple documents:
index.deleteDocuments(documentsIds: string[] | number[]): Promise<EnqueuedUpdate>
- Delete all documents:
index.deleteAllDocuments(): Promise<Types.EnqueuedUpdate>
Settings
- Get settings:
index.getSettings(): Promise<Settings>
- Update settings:
index.updateSettings(settings: Settings): Promise<EnqueuedUpdate>
- Reset settings:
index.resetSettings(): Promise<EnqueuedUpdate>
Synonyms
- Get synonyms:
index.getSynonyms(): Promise<object>
- Update synonyms:
index.updateSynonym(synonyms: object): Promise<EnqueuedUpdate>
- Reset synonyms:
index.resetSynonym(): Promise<EnqueuedUpdate>
Stop-words
-
Get Stop Words
index.getStopWords(): Promise<string[]>
-
Update Stop Words
index.updateStopWords(string[]): Promise<EnqueuedUpdate>
-
Reset Stop Words
index.resetStopWords(): Promise<EnqueuedUpdate>
Ranking rules
-
Get Ranking Rules
index.getRankingRules(): Promise<string[]>
-
Update Ranking Rules
index.updateRankingRules(rankingRules: string[]): Promise<EnqueuedUpdate>
-
Reset Ranking Rules
index.resetRankingRules(): Promise<EnqueuedUpdate>
Distinct Attribute
-
Get Distinct Attribute
index.getDistinctAttribute(): Promise<string | void>
-
Update Distinct Attribute
index.updateDistinctAttribute(distinctAttribute: string): Promise<EnqueuedUpdate>
-
Reset Distinct Attribute
index.resetDistinctAttribute(): Promise<EnqueuedUpdate>
Searchable Attributes
-
Get Searchable Attributes
index.getSearchableAttributes(): Promise<string[]>
-
Update Searchable Attributes
index.updateSearchableAttributes(searchableAttributes: string[]): Promise<EnqueuedUpdate>
-
Reset Searchable Attributes
index.resetSearchableAttributes(): Promise<EnqueuedUpdate>
Displayed Attributes
-
Get Displayed Attributes
index.getDisplayedAttributes(): Promise<string[]>
-
Update Displayed Attributes
index.updateDisplayedAttributes(displayedAttributes: string[]): Promise<EnqueuedUpdate>
-
Reset Displayed Attributes
index.resetDisplayedAttributes(): Promise<EnqueuedUpdate>
- Get keys
client.getKeys(): Promise<Keys>
Healthy
- Check if the server is healthy
client.isHealthy(): Promise<true>
Stats
- Get database stats
client.stats(): Promise<Stats>
Version
- Get binary version
client.version(): Promise<Version>
Dumps
- Trigger a dump creation process
client.createDump(): Promise<Types.EnqueuedDump>
- Get the status of a dump creation process
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.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK