Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

JavaScript client for the Meilisearch API

License

NotificationsYou must be signed in to change notification settings

consoleLogIt/meilisearch-js

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Meilisearch-JavaScript

Meilisearch JavaScript

npm versionTestsCodecovPrettierLicenseBors 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.Learn more about Meilisearch.

Table of Contents

📖 Documentation

This readme andMeilisearch JS documentation website contains all the information you need to start using this Meilisearch SDK.

For general information on how to use Meilisearch—such as our API reference, tutorials, guides, and in-depth articles—refer to ourmain documentation website.

🔧 Installation

This package is published tonpm.

Installing withnpm:

npm i meilisearch

Note

Node.jsLTS and Maintenance versionsare supported and tested. Other versions may or may not work.

Other runtimes, like Deno and Bun, aren't tested, but if they do not work withthis package, please open an issue.

Run Meilisearch

⚡️Launch, scale, and streamline in minutes with Meilisearch Cloud—no maintenance, no commitment, cancel anytime.Try it free now.

🪨 Prefer to self-host?Download and deploy our fast, open-source search engine on your own infrastructure.

Import

After installingmeilisearch-js, you must import it into your application. There are many ways of doing that depending on your development environment.

⚠️ If any issues arise importingmeilisearch/token

Warning

  • default exportis deprecated and will be removed in a future version |Issue
  • regarding usage of package's UMD version viascript src, exports will stopbeing directly available on theglobal object|Issue

import syntax

Usage in an ES module environment:

import{MeiliSearch}from"meilisearch";constclient=newMeiliSearch({host:"http://127.0.0.1:7700",apiKey:"masterKey",});

<script> tag

This package also contains aUMD bundledversion, which in this case is meant to be used in ascript srctag:

<scriptsrc="https://www.unpkg.com/meilisearch/dist/umd/index.min.js"></script><script>constclient=newmeilisearch.MeiliSearch(/* ... */);// ...</script>

But keep in mind that each CDN (JSDELIVR,ESM.SH, etc.) provide more ways to import packages, make sureto read their documentation.

require syntax

Usage in a back-end node.js or another environment supporting CommonJS modules:

const{ MeiliSearch}=require("meilisearch");constclient=newMeiliSearch({host:"http://127.0.0.1:7700",apiKey:"masterKey",});

React Native

To usemeilisearch-js with React Native, you must also installreact-native-url-polyfill.

Deno

Usage in a Deno environment:

import{MeiliSearch}from"npm:meilisearch";constclient=newMeiliSearch({host:"http://127.0.0.1:7700",apiKey:"masterKey",});

🚀 Getting started

Take a look at theplayground for a concrete example.

Add documents

const{ MeiliSearch}=require('meilisearch')// Or if you are in a ES environmentimport{MeiliSearch}from'meilisearch';(async()=>{constclient=newMeiliSearch({host:'http://127.0.0.1:7700',apiKey:'masterKey',})// An index is where the documents are stored.constindex=client.index('movies')constdocuments=[{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.letresponse=awaitindex.addDocuments(documents)console.log(response)// => { "uid": 0 }})()

Tasks such as document addition always return a unique identifier. You can use this identifiertaskUid to check the status (enqueued,canceled,processing,succeeded orfailed) of atask.

Basic search

// Meilisearch is typo-tolerant:constsearch=awaitindex.search('philoudelphia')console.log(search)

Output:

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

Using search parameters

meilisearch-js supports allsearch parameters described in our main documentation website.

awaitindex.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,"estimatedTotalHits":1,"processingTimeMs":0,"query":"wonder"}

Custom search with filters

To enable filtering, you must first add your attributes to thefilterableAttributes index setting.

awaitindex.updateFilterableAttributes(['id','genres'])

You only need to perform this operation once per index.

Note that Meilisearch rebuilds your index whenever you updatefilterableAttributes. Depending on the size of your dataset, this might take considerable time. You can track the process using thetasks API).

After you configuredfilterableAttributes, you can use thefilter search parameter to refine your search:

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

Placeholder search

Placeholder search makes it possible to receive hits based on your parameters without having any query (q). For example, in a movies database you can run an empty query to receive all results filtered bygenre.

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

Note that to enable faceted search on your dataset you need to addgenres to thefilterableAttributes index setting. For more information on filtering and faceting,consult our documentation settings.

Abortable search

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

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

Using Meilisearch behind a proxy

Custom request config

You can provide a custom request configuration. for example, with custom headers.

constclient:MeiliSearch=newMeiliSearch({host:'http://localhost:3000/api/meilisearch/proxy',requestConfig:{headers:{Authorization:AUTH_TOKEN},// ORcredentials:'include'}})

Custom http client

You can use your own HTTP client, for example, withaxios.

constclient:MeiliSearch=newMeiliSearch({host:'http://localhost:3000/api/meilisearch/proxy',httpClient:async(url,opts)=>{constresponse=await$axios.request({      url,data:opts?.body,headers:opts?.headers,method:(opts?.method?.toLocaleUpperCase()asMethod)??'GET'})returnresponse.data}})

🤖 Compatibility with Meilisearch

This package guarantees compatibility withversion v1.x of Meilisearch, but some features may not be present. Please check theissues for more info.

💡 Learn more

The following sections in our main documentation website may interest you:

This repository also containsmore examples.

⚙️ Contributing

We welcome all contributions, big and small! If you want to know more about this SDK's development workflow or want to contribute to the repo, please visit ourcontributing 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>>

Multi Search

client.multiSearch(queries?:MultiSearchParams,config?:Partial<Request>):Promise<Promise<MultiSearchResponse<T>>>

multiSearch uses thePOST method when performing its request to Meilisearch.

Search For Facet Values

client.index<T>('myIndex').searchForFacetValues(params:SearchForFacetValuesParams,config?:Partial<Request>):Promise<SearchForFacetValuesResponse>

Documents

client.index('myIndex').addDocuments(documents:Document<T>[]):Promise<EnqueuedTask>
client.index('myIndex').addDocumentsFromString(documents: string,contentType:ContentType,queryParams:RawDocumentAdditionOptions):Promise<EnqueuedTask>
client.index('myIndex').addDocumentsInBatches(documents:Document<T>[],batchSize=1000):Promise<EnqueuedTask[]>
client.index('myIndex').updateDocuments(documents:Array<Document<Partial<T>>>):Promise<EnqueuedTask>
client.index('myIndex').updateDocumentsFromString(documents: string,contentType:ContentType,queryParams:RawDocumentAdditionOptions):Promise<EnqueuedTask>
client.index('myIndex').updateDocumentsInBatches(documents:Array<Document<Partial<T>>>,batchSize=1000):Promise<EnqueuedTask[]>
client.index.getDocuments(parameters:DocumentsQuery={}):Promise<DocumentsResults<T>>>
client.index('myIndex').getDocument(documentId: string):Promise<Document<T>>
client.index('myIndex').deleteDocument(documentId: string|number):Promise<EnqueuedTask>
client.index('myIndex').deleteDocuments(params:DocumentsDeletionQuery|DocumentsIds):Promise<EnqueuedTask>
client.index('myIndex').deleteAllDocuments():Promise<Types.EnqueuedTask>

Tasks

client.getTasks(parameters:TasksQuery):Promise<TasksResults>
client.getTask(uid:number):Promise<Task>
client.deleteTasks(parameters:DeleteTasksQuery={}):Promise<EnqueuedTask>
client.cancelTasks(parameters:CancelTasksQuery={}):Promise<EnqueuedTask>
client.index('myIndex').getTasks(parameters:TasksQuery):Promise<TasksResults>
client.index('myIndex').getTask(uid:number):Promise<Task>

Wait for one task

Using the client
client.waitForTask(uid:number,{timeOutMs?:number,intervalMs?:number}):Promise<Task>
Using the index
client.index('myIndex').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<Task[]>
Using the index
client.index('myIndex').waitForTasks(uids:number[],{timeOutMs?:number,intervalMs?:number}):Promise<Task[]>

Batches

client.getBatch(uid:number):Promise<Batch>
client.getBatches(parameters:BatchesQuery={}):Promise<BatchesResults>

Indexes

client.getIndexes(parameters:IndexesQuery):Promise<IndexesResults<Index[]>>
client.getRawIndexes(parameters:IndexesQuery):Promise<IndexesResults<IndexObject[]>>
client.createIndex<T>(uid:string,options?:IndexOptions):Promise<EnqueuedTask>

Create a local reference to an index

client.index<T>(uid:string):Index<T>
client.getIndex<T>(uid:string):Promise<Index<T>>
client.getRawIndex(uid:string):Promise<IndexObject>
client.index('myIndex').getRawInfo():Promise<IndexObject>
Using the client
client.updateIndex(uid:string,options:IndexOptions):Promise<EnqueuedTask>
Using the index object
client.index('myIndex').update(data:IndexOptions):Promise<EnqueuedTask>
Using the client
client.deleteIndex(uid):Promise<void>
Using the index object
client.index('myIndex').delete():Promise<void>
client.index('myIndex').getStats():Promise<IndexStats>
Return Index instance with updated information
client.index('myIndex').fetchInfo():Promise<Index>
Get Primary Key of an Index
client.index('myIndex').fetchPrimaryKey():Promise<string|undefined>
Swap two indexes
client.swapIndexes(params:SwapIndexesParams):Promise<EnqueuedTask>

Settings

client.index('myIndex').getSettings():Promise<Settings>
client.index('myIndex').updateSettings(settings:Settings):Promise<EnqueuedTask>
client.index('myIndex').resetSettings():Promise<EnqueuedTask>

Pagination Settings

client.index('myIndex').getPagination():Promise<PaginationSettings>
client.index('myIndex').updatePagination(pagination:PaginationSettings):Promise<EnqueuedTask>
client.index('myIndex').resetPagination():Promise<EnqueuedTask>

Synonyms

client.index('myIndex').getSynonyms():Promise<Synonyms>
client.index('myIndex').updateSynonyms(synonyms:Synonyms):Promise<EnqueuedTask>
client.index('myIndex').resetSynonyms():Promise<EnqueuedTask>

Stop words

client.index('myIndex').getStopWords():Promise<string[]>
client.index('myIndex').updateStopWords(stopWords: string[]|null):Promise<EnqueuedTask>
client.index('myIndex').resetStopWords():Promise<EnqueuedTask>

Ranking rules

client.index('myIndex').getRankingRules():Promise<string[]>
client.index('myIndex').updateRankingRules(rankingRules: string[]|null):Promise<EnqueuedTask>
client.index('myIndex').resetRankingRules():Promise<EnqueuedTask>

Distinct Attribute

client.index('myIndex').getDistinctAttribute():Promise<string|void>
client.index('myIndex').updateDistinctAttribute(distinctAttribute: string|null):Promise<EnqueuedTask>
client.index('myIndex').resetDistinctAttribute():Promise<EnqueuedTask>

Searchable attributes

client.index('myIndex').getSearchableAttributes():Promise<string[]>
client.index('myIndex').updateSearchableAttributes(searchableAttributes: string[]|null):Promise<EnqueuedTask>
client.index('myIndex').resetSearchableAttributes():Promise<EnqueuedTask>

Displayed attributes

client.index('myIndex').getDisplayedAttributes():Promise<string[]>
client.index('myIndex').updateDisplayedAttributes(displayedAttributes: string[]|null):Promise<EnqueuedTask>
client.index('myIndex').resetDisplayedAttributes():Promise<EnqueuedTask>

Filterable attributes

client.index('myIndex').getFilterableAttributes():Promise<string[]>
client.index('myIndex').updateFilterableAttributes(filterableAttributes: string[]|null):Promise<EnqueuedTask>
client.index('myIndex').resetFilterableAttributes():Promise<EnqueuedTask>

Sortable attributes

client.index('myIndex').getSortableAttributes():Promise<string[]>
client.index('myIndex').updateSortableAttributes(sortableAttributes: string[]|null):Promise<EnqueuedTask>
client.index('myIndex').resetSortableAttributes():Promise<EnqueuedTask>

Faceting

client.index('myIndex').getFaceting():Promise<Faceting>
client.index('myIndex').updateFaceting(faceting:Faceting):Promise<EnqueuedTask>
client.index('myIndex').resetFaceting():Promise<EnqueuedTask>

Typo tolerance

client.index('myIndex').getTypoTolerance():Promise<TypoTolerance>
client.index('myIndex').updateTypoTolerance(typoTolerance:TypoTolerance|null):Promise<EnqueuedTask>
client.index('myIndex').resetTypoTolerance():Promise<EnqueuedTask>

Separator tokens

client.index('myIndex').getSeparatorTokens():Promise<SeparatorTokens>
client.index('myIndex').updateSeparatorTokens(separatorTokens:SeparatorTokens|null):Promise<EnqueuedTask>
client.index('myIndex').resetSeparatorTokens():Promise<EnqueuedTask>

Non Separator tokens

client.index('myIndex').getNonSeparatorTokens():Promise<NonSeparatorTokens>
client.index('myIndex').updateNonSeparatorTokens(nonSeparatorTokens:NonSeparatorTokens|null):Promise<EnqueuedTask>
client.index('myIndex').resetNonSeparatorTokens():Promise<EnqueuedTask>

Dictionary

client.index('myIndex').getDictionary():Promise<Dictionary>
client.index('myIndex').updateDictionary(dictionary:Dictionary|null):Promise<EnqueuedTask>
client.index('myIndex').resetDictionary():Promise<EnqueuedTask>

Proximity Precision

client.index('myIndex').getProximityPrecision():Promise<ProximityPrecision>
client.index('myIndex').updateProximityPrecision(proximityPrecision:ProximityPrecision):Promise<EnqueuedTask>
client.index('myIndex').resetProximityPrecision():Promise<EnqueuedTask>

Facet search settings

client.index('myIndex').getFacetSearch():Promise<boolean>
client.index('myIndex').updateFacetSearch(enabled:boolean):Promise<EnqueuedTask>
client.index('myIndex').resetFacetSearch():Promise<EnqueuedTask>

Prefix search settings

client.index('myIndex').getPrefixSearch():Promise<PrefixSearch>
client.index('myIndex').updatePrefixSearch(prefixSearch:PrefixSearch):Promise<EnqueuedTask>
client.index('myIndex').resetPrefixSearch():Promise<EnqueuedTask>

Embedders

Get embedders

client.index('myIndex').getEmbedders():Promise<Embedders>

Update embedders

client.index('myIndex').updateEmbedders(embedders:Embedders):Promise<EnqueuedTask>

Reset embedders

client.index('myIndex').resetEmbedders():Promise<EnqueuedTask>

SearchCutoffMs

client.index('myIndex').getSearchCutoffMs():Promise<SearchCutoffMs>
client.index('myIndex').updateSearchCutoffMs(searchCutoffMs:SearchCutoffMs):Promise<EnqueuedTask>
client.index('myIndex').resetSearchCutoffMs():Promise<EnqueuedTask>

Keys

client.getKeys(parameters:KeysQuery):Promise<KeysResults>
client.getKey(keyOrUid: string):Promise<Key>
client.createKey(options:KeyCreation):Promise<Key>
client.updateKey(keyOrUid: string,options:KeyUpdate):Promise<Key>
client.deleteKey(keyOrUid: 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<EnqueuedTask>

Snapshots

client.createSnapshot():Promise<EnqueuedTask>

Meilisearch provides and maintains many SDKs and integration tools like this one. We want to provide everyone with anamazing search experience for any kind of project. For a full overview of everything we create and maintain, take a look at theintegration-guides repository.

About

JavaScript client for the Meilisearch API

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • TypeScript97.2%
  • CSS1.8%
  • Other1.0%

[8]ページ先頭

©2009-2025 Movatter.jp