### Install project dependencies
Source: https://github.com/meilisearch/meilisearch-java/blob/main/CONTRIBUTING.md
Builds the project and installs necessary dependencies using Gradle.
```bash
./gradlew build
```
--------------------------------
### Update Version in README.md (Installation)
Source: https://github.com/meilisearch/meilisearch-java/blob/main/CONTRIBUTING.md
Update the version in the README.md file within the Installation section.
```xml
X.X.X
```
--------------------------------
### Install GPG for Signing
Source: https://github.com/meilisearch/meilisearch-java/blob/main/CONTRIBUTING.md
Install the gnupg package on Debian/Ubuntu systems or use Homebrew on macOS to manage GPG keys.
```bash
sudo apt install gnupg
```
```bash
brew install gpg
```
--------------------------------
### Install Meilisearch Java via Gradle
Source: https://github.com/meilisearch/meilisearch-java/blob/main/README.md
Add this implementation line to the dependencies section of your build.gradle file.
```groovy
implementation 'com.meilisearch.sdk:meilisearch-java:0.20.0'
```
--------------------------------
### Install Meilisearch Java via Maven
Source: https://github.com/meilisearch/meilisearch-java/blob/main/README.md
Add this dependency to the dependencies section of your pom.xml file.
```xml
com.meilisearch.sdk
meilisearch-java
0.20.0
pom
```
--------------------------------
### Meilisearch Instance Operations
Source: https://context7.com/meilisearch/meilisearch-java/llms.txt
Perform instance-level operations such as checking health, getting version information, retrieving statistics, and managing backups. Use `waitForTask` to ensure operations complete.
```java
import com.meilisearch.sdk.model.Stats;
import com.meilisearch.sdk.model.IndexStats;
import com.meilisearch.sdk.model.TaskInfo;
// Check if Meilisearch is healthy
boolean healthy = client.isHealthy();
String healthStatus = client.health(); // Returns JSON string
// Get Meilisearch version
String version = client.getVersion();
// Get global statistics
Stats stats = client.getStats();
System.out.println("Database size: " + stats.getDatabaseSize());
System.out.println("Last update: " + stats.getLastUpdate());
// Get statistics for a specific index
IndexStats indexStats = index.getStats();
System.out.println("Number of documents: " + indexStats.getNumberOfDocuments());
System.out.println("Is indexing: " + indexStats.isIndexing());
// Create a database dump (backup)
TaskInfo dumpTask = client.createDump();
client.waitForTask(dumpTask.getTaskUid());
// Create a database snapshot
TaskInfo snapshotTask = client.createSnapshot();
client.waitForTask(snapshotTask.getTaskUid());
// Compact an index to reclaim space
TaskInfo compactTask = index.compact();
index.waitForTask(compactTask.getTaskUid());
// Enable experimental features
Map features = new HashMap<>();
features.put("vectorStore", true);
client.experimentalFeatures(features);
```
--------------------------------
### Build, Sign, and Upload to Maven
Source: https://github.com/meilisearch/meilisearch-java/blob/main/CONTRIBUTING.md
Execute the Maven command to build the project, sign the artifacts using the provided GPG key, and upload them to the Maven repository.
```bash
# build, sign your files and upload them to Maven repository:
```
--------------------------------
### Initialize Meilisearch Client
Source: https://context7.com/meilisearch/meilisearch-java/llms.txt
Configure the client with host URL, optional API keys, custom JSON handlers, or client agents.
```java
import com.meilisearch.sdk.Client;
import com.meilisearch.sdk.Config;
import com.meilisearch.sdk.json.JacksonJsonHandler;
// Basic initialization with API key
Client client = new Client(new Config("http://localhost:7700", "masterKey"));
// Initialization without API key (for development)
Client client = new Client(new Config("http://localhost:7700"));
// Using Jackson instead of Gson for JSON handling
Config config = new Config("http://localhost:7700", "masterKey", new JacksonJsonHandler());
Client client = new Client(config);
// With custom client agents
Config config = new Config("http://localhost:7700", "masterKey", new String[]{"MyApp/1.0"});
Client client = new Client(config);
```
--------------------------------
### Manage Index Settings in Java
Source: https://context7.com/meilisearch/meilisearch-java/llms.txt
Demonstrates how to retrieve, update, and reset index settings such as ranking rules, synonyms, typo tolerance, and pagination limits.
```java
import com.meilisearch.sdk.model.Settings;
import com.meilisearch.sdk.model.TypoTolerance;
import com.meilisearch.sdk.model.Pagination;
import com.meilisearch.sdk.model.Faceting;
import java.util.HashMap;
Index index = client.index("movies");
// Get all settings
Settings settings = index.getSettings();
// Update multiple settings at once
Settings newSettings = new Settings();
newSettings.setSearchableAttributes(new String[]{"title", "overview", "genres"});
newSettings.setFilterableAttributes(new String[]{"genres", "release_year", "language"});
newSettings.setSortableAttributes(new String[]{"release_year", "title"});
newSettings.setDisplayedAttributes(new String[]{"title", "overview", "poster", "genres"});
newSettings.setRankingRules(new String[]{
"words", "typo", "proximity", "attribute", "sort", "exactness"
});
TaskInfo task = index.updateSettings(newSettings);
index.waitForTask(task.getTaskUid());
// Reset all settings to defaults
TaskInfo task = index.resetSettings();
// Configure stop words
index.updateStopWordsSettings(new String[]{"the", "a", "an", "of"});
// Configure synonyms
HashMap synonyms = new HashMap<>();
synonyms.put("movie", new String[]{"film", "picture"});
synonyms.put("good", new String[]{"great", "excellent", "awesome"});
index.updateSynonymsSettings(synonyms);
// Configure distinct attribute (for deduplication)
index.updateDistinctAttributeSettings("movie_id");
// Configure typo tolerance
TypoTolerance typoTolerance = new TypoTolerance();
typoTolerance.setEnabled(true);
typoTolerance.setDisableOnWords(new String[]{"ISBN", "UUID"});
typoTolerance.setDisableOnAttributes(new String[]{"id", "sku"});
HashMap minWordSize = new HashMap<>();
minWordSize.put("oneTypo", 5);
minWordSize.put("twoTypos", 9);
typoTolerance.setMinWordSizeForTypos(minWordSize);
index.updateTypoToleranceSettings(typoTolerance);
// Configure pagination limits
Pagination pagination = new Pagination();
pagination.setMaxTotalHits(1000);
index.updatePaginationSettings(pagination);
// Configure faceting
Faceting faceting = new Faceting();
faceting.setMaxValuesPerFacet(100);
index.updateFacetingSettings(faceting);
// Configure proximity precision
index.updateProximityPrecisionSettings("byWord"); // or "byAttribute"
// Configure search cutoff (max search time in ms)
index.updateSearchCutoffMsSettings(1500);
// Configure separator tokens
index.updateSeparatorTokensSettings(new String[]{"@", "#"});
// Configure non-separator tokens
index.updateNonSeparatorTokensSettings(new String[]{"@", "_"});
// Configure dictionary (for domain-specific terms)
index.updateDictionarySettings(new String[]{"NYC", "AI", "ML"});
```
--------------------------------
### Run integration tests
Source: https://github.com/meilisearch/meilisearch-java/blob/main/CONTRIBUTING.md
Downloads and runs a local Meilisearch instance, then executes integration tests.
```bash
curl -L https://install.meilisearch.com | sh # download Meilisearch
./meilisearch --master-key=masterKey --no-analytics # run Meilisearch
./gradlew test IntegrationTest
```
--------------------------------
### Create GPG Key Configuration
Source: https://github.com/meilisearch/meilisearch-java/blob/main/CONTRIBUTING.md
Create a genkey file with parameters for generating a new GPG key, including key type, length, and expiration.
```bash
Key-Type: 1
Key-Length: 4096
Subkey-Type: 1
Subkey-Length: 4096
Name-Real:
Name-Email:
Expire-Date: 0
Passphrase:
```
--------------------------------
### Configure and Implement JSON Handlers
Source: https://context7.com/meilisearch/meilisearch-java/llms.txt
Demonstrates how to initialize the Meilisearch client with different JSON handlers, including Gson, Jackson, and a custom implementation.
```java
import com.meilisearch.sdk.Config;
import com.meilisearch.sdk.Client;
import com.meilisearch.sdk.json.GsonJsonHandler;
import com.meilisearch.sdk.json.JacksonJsonHandler;
import com.meilisearch.sdk.json.JsonHandler;
import com.fasterxml.jackson.databind.ObjectMapper;
// Using default Gson handler
Config gsonConfig = new Config("http://localhost:7700", "masterKey");
Client gsonClient = new Client(gsonConfig);
// Using Jackson handler
Config jacksonConfig = new Config("http://localhost:7700", "masterKey", new JacksonJsonHandler());
Client jacksonClient = new Client(jacksonConfig);
// Using Jackson with custom ObjectMapper
ObjectMapper customMapper = new ObjectMapper();
customMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Config customJacksonConfig = new Config("http://localhost:7700", "masterKey",
new JacksonJsonHandler(customMapper));
Client customClient = new Client(customJacksonConfig);
// Implementing a custom JSON handler
public class CustomJsonHandler implements JsonHandler {
@Override
public String encode(Object o) throws MeilisearchException {
// Custom serialization logic
return serializedString;
}
@Override
public T decode(Object o, Class targetClass, Class>... parameters)
throws MeilisearchException {
// Custom deserialization logic
return deserializedObject;
}
}
```
--------------------------------
### Basic Search with Offset/Limit Pagination
Source: https://context7.com/meilisearch/meilisearch-java/llms.txt
Perform a basic search query with offset and limit for pagination. Ensure the 'adventure' query and pagination parameters are set.
```java
import com.meilisearch.sdk.SearchRequest;
import com.meilisearch.sdk.model.SearchResult;
import com.meilisearch.sdk.model.SearchResultPaginated;
import com.meilisearch.sdk.model.Searchable;
import com.meilisearch.sdk.model.MatchingStrategy;
Index index = client.index("movies");
// Search with offset/limit pagination
SearchRequest request = SearchRequest.builder()
.q("adventure")
.offset(0)
.limit(10)
.build();
SearchResult results = (SearchResult) index.search(request);
```
--------------------------------
### Initialize Client with JacksonJsonHandler
Source: https://github.com/meilisearch/meilisearch-java/blob/main/README.md
Configure the Meilisearch client using the provided JacksonJsonHandler implementation.
```java
import com.meilisearch.sdk.json.JacksonJsonHandler;
Config config = new Config("http://localhost:7700", "masterKey", new JacksonJsonHandler());
Client client = new Client(config);
```
--------------------------------
### Run unit tests
Source: https://github.com/meilisearch/meilisearch-java/blob/main/CONTRIBUTING.md
Executes the project's unit test suite.
```bash
./gradlew test
```
--------------------------------
### Initialize Client with Custom JsonHandler
Source: https://github.com/meilisearch/meilisearch-java/blob/main/README.md
Use a custom JSON handler implementation when initializing the Meilisearch configuration.
```java
Config config = new Config("http://localhost:7700", "masterKey", new myJsonHandler());
Client client = new Client(config);
```
--------------------------------
### Set Maven Credentials and Signing Key
Source: https://github.com/meilisearch/meilisearch-java/blob/main/CONTRIBUTING.md
Configure environment variables for Maven Central username and password, and GPG key ID and passphrase for signing artifacts.
```bash
export MAVEN_CENTRAL_USERNAME=
export MAVEN_CENTRAL_PASSWORD=
export SIGNINT_KEY_ID=
export SIGNING_PASSWORD=
```
--------------------------------
### Run project linter
Source: https://github.com/meilisearch/meilisearch-java/blob/main/CONTRIBUTING.md
Executes the linting script to ensure code quality standards.
```bash
bash ./scripts/lint.sh
```
--------------------------------
### Configure Granular Filterable Attributes in Java
Source: https://context7.com/meilisearch/meilisearch-java/llms.txt
Shows how to define fine-grained filtering and facet search capabilities for specific attributes to optimize index performance.
```java
import com.meilisearch.sdk.model.FilterableAttributesConfig;
import com.meilisearch.sdk.model.FilterableAttributesFeatures;
Index index = client.index("movies");
// Configure granular filterable attributes
FilterableAttributesConfig genresConfig = new FilterableAttributesConfig("genres");
FilterableAttributesFeatures genresFeatures = new FilterableAttributesFeatures()
.setFacetSearch(true)
.setFilter(true);
genresConfig.setFeatures(genresFeatures);
FilterableAttributesConfig yearConfig = new FilterableAttributesConfig("release_year");
FilterableAttributesFeatures yearFeatures = new FilterableAttributesFeatures()
.setFacetSearch(false)
.setFilter(true);
yearConfig.setFeatures(yearFeatures);
FilterableAttributesConfig[] configs = new FilterableAttributesConfig[]{genresConfig, yearConfig};
TaskInfo task = index.updateGranularFilterableAttributesSettings(configs);
index.waitForTask(task.getTaskUid());
// Retrieve granular settings
FilterableAttributesConfig[] currentConfigs = index.getGranularFilterableAttributesSettings();
```
--------------------------------
### Search with Matching Strategy
Source: https://context7.com/meilisearch/meilisearch-java/llms.txt
Define the matching strategy for queries. Use 'ALL' to match all query terms or 'LAST' to match the last query term.
```java
// Search with matching strategy
SearchRequest request = SearchRequest.builder()
.q("big adventure movie")
.matchingStrategy(MatchingStrategy.ALL) // ALL or LAST
.build();
```
--------------------------------
### Perform Basic Search in Meilisearch Java SDK
Source: https://context7.com/meilisearch/meilisearch-java/llms.txt
Execute full-text searches on an index. The SDK handles typo tolerance and relevance ranking automatically. You can retrieve search results, including hits and processing time.
```java
import com.meilisearch.sdk.Index;
import com.meilisearch.sdk.model.SearchResult;
import java.util.ArrayList;
import java.util.HashMap;
Index index = client.index("movies");
// Basic search with query string
SearchResult results = index.search("wonder woman");
System.out.println("Found " + results.getEstimatedTotalHits() + " results");
System.out.println("Processing time: " + results.getProcessingTimeMs() + "ms");
// Access search hits
ArrayList> hits = results.getHits();
for (HashMap hit : hits) {
System.out.println("Title: " + hit.get("title"));
System.out.println("Genres: " + hit.get("genres"));
}
// Typo-tolerant search (automatically handles misspellings)
SearchResult results = index.search("woder womn"); // Still finds "Wonder Woman"
// Get raw JSON response
String rawResults = index.rawSearch("batman");
```
--------------------------------
### Manage Meilisearch Webhooks
Source: https://context7.com/meilisearch/meilisearch-java/llms.txt
Use these methods to list, retrieve, create, update, and delete webhooks. Ensure you have the correct webhook IDs and request objects for each operation.
```java
import com.meilisearch.sdk.model.Webhook;
import com.meilisearch.sdk.model.CreateUpdateWebhookRequest;
import com.meilisearch.sdk.model.Results;
import java.util.UUID;
import java.util.Map;
import java.util.HashMap;
// List all webhooks
Results webhooks = client.getWebhooks();
// Get a specific webhook
UUID webhookId = UUID.fromString("webhook-uuid-here");
Webhook webhook = client.getWebhook(webhookId);
// Create a new webhook
CreateUpdateWebhookRequest createRequest = new CreateUpdateWebhookRequest();
createRequest.setUrl("https://myapp.example.com/webhooks/meilisearch");
Map headers = new HashMap<>();
headers.put("Authorization", "Bearer my-secret-token");
createRequest.setHeaders(headers);
Webhook newWebhook = client.createWebhook(createRequest);
// Update a webhook
CreateUpdateWebhookRequest updateRequest = new CreateUpdateWebhookRequest();
updateRequest.setUrl("https://myapp.example.com/webhooks/new-endpoint");
Webhook updatedWebhook = client.updateWebhook(newWebhook.getUid(), updateRequest);
// Delete a webhook
client.deleteWebhook(newWebhook.getUid());
```
--------------------------------
### Generate Tenant Tokens in Java
Source: https://context7.com/meilisearch/meilisearch-java/llms.txt
Create JWT-based tenant tokens to enforce search rules for specific users. These tokens can be safely shared with frontend applications.
```java
import com.meilisearch.sdk.TenantTokenOptions;
import java.util.HashMap;
import java.util.Map;
import java.util.Date;
// Define search rules
Map searchRules = new HashMap<>();
// Allow searching all indexes
searchRules.put("*", new HashMap<>());
// Or restrict to specific indexes with filters
Map moviesRules = new HashMap<>();
moviesRules.put("filter", "user_id = 123");
searchRules.put("movies", moviesRules);
// Generate token with default options (uses client's API key)
String apiKeyUid = "api-key-uid-here"; // Must be valid UUID4
String token = client.generateTenantToken(apiKeyUid, searchRules);
// Generate token with custom options
TenantTokenOptions options = new TenantTokenOptions();
options.setApiKey("specific-api-key-value");
options.setExpiresAt(new Date(System.currentTimeMillis() + 3600000)); // 1 hour expiry
String token = client.generateTenantToken(apiKeyUid, searchRules, options);
// Use the token for client-side search
// This token can be safely shared with frontend applications
```
--------------------------------
### Publish Public GPG Key
Source: https://github.com/meilisearch/meilisearch-java/blob/main/CONTRIBUTING.md
Send your public GPG key to a public keyserver using its hash, allowing others to verify your identity.
```bash
gpg --keyserver hkp://keyserver.ubuntu.com --send-keys
```
--------------------------------
### Search with Highlighting
Source: https://context7.com/meilisearch/meilisearch-java/llms.txt
Configure highlighting to emphasize search terms within the result snippets. Specify attributes to highlight and the pre/post tags for emphasis.
```java
// Search with highlighting
SearchRequest request = SearchRequest.builder()
.q("adventure")
.attributesToHighlight(new String[]{"title", "overview"})
.highlightPreTag("")
.highlightPostTag("")
.build();
```
--------------------------------
### Generate GPG Key
Source: https://github.com/meilisearch/meilisearch-java/blob/main/CONTRIBUTING.md
Generate a GPG key using the batch mode with the specified configuration file. May require sudo privileges.
```bash
# May need sudo privilege
gpg --gen-key --batch genkey
```
--------------------------------
### Configure Embedders for Hybrid Search
Source: https://context7.com/meilisearch/meilisearch-java/llms.txt
Set up AI embedders for hybrid search. This involves defining embedder sources, API keys, models, and document templates.
```java
import com.meilisearch.sdk.SearchRequest;
import com.meilisearch.sdk.model.Hybrid;
import com.meilisearch.sdk.model.Embedder;
import com.meilisearch.sdk.model.EmbedderSource;
import java.util.HashMap;
import java.util.Map;
Index index = client.index("movies");
// First, configure embedders in index settings
Map embedders = new HashMap<>();
Embedder openAiEmbedder = Embedder.builder()
.source(EmbedderSource.OPEN_AI)
.apiKey("sk-your-openai-key")
.model("text-embedding-ada-002")
.documentTemplate("A movie titled '{{doc.title}}' about {{doc.overview}}")
.build();
embedders.put("openai", openAiEmbedder);
index.updateEmbeddersSettings(embedders);
```
--------------------------------
### Search with Page-Based Pagination
Source: https://context7.com/meilisearch/meilisearch-java/llms.txt
Implement page-based pagination by setting the page number and hits per page. This is an alternative to offset/limit pagination.
```java
// Search with page-based pagination
SearchRequest request = new SearchRequest("adventure")
.setPage(1)
.setHitsPerPage(20);
SearchResultPaginated results = (SearchResultPaginated) index.search(request);
System.out.println("Page " + results.getPage() + " of " + results.getTotalPages());
```
--------------------------------
### Run project checks with Docker
Source: https://github.com/meilisearch/meilisearch-java/blob/main/CONTRIBUTING.md
Executes build and integration tests within a Docker container environment.
```bash
docker-compose run --rm package bash -c "./gradlew build && ./gradlew build integrationTest"
```
--------------------------------
### Instance Operations API
Source: https://context7.com/meilisearch/meilisearch-java/llms.txt
Endpoints for monitoring server health, retrieving version information, gathering statistics, and performing administrative tasks like dumps and snapshots.
```APIDOC
## Instance Operations
### Description
Perform administrative operations on the Meilisearch instance.
### Methods
- GET /health (Check health)
- GET /version (Get version)
- GET /stats (Global stats)
- GET /indexes/{indexUid}/stats (Index stats)
- POST /dumps (Create dump)
- POST /snapshots (Create snapshot)
- POST /indexes/{indexUid}/compact (Compact index)
- PATCH /experimental-features (Enable features)
### Request Body (Experimental Features)
- **features** (Map) - Required - Map of feature names to enabled status.
```
--------------------------------
### Perform a basic search
Source: https://github.com/meilisearch/meilisearch-java/blob/main/README.md
Executes a simple string query against an index. Meilisearch provides built-in typo tolerance.
```java
import com.meilisearch.sdk.model.SearchResult;
// Meilisearch is typo-tolerant:
SearchResult results = index.search("carlo");
System.out.println(results);
```
```text
SearchResult(hits=[{id=1.0, title=Carol, genres:[Romance, Drama]}], offset=0, limit=20, estimatedTotalHits=1, facetDistribution=null, processingTimeMs=3, query=carlo)
```
--------------------------------
### Add Meilisearch Java Dependency
Source: https://github.com/meilisearch/meilisearch-java/blob/main/CONTRIBUTING.md
Include the Meilisearch Java client as a dependency in your project's build file, specifying the version.
```groovy
implementation 'com.meilisearch.sdk:meilisearch-java:X.X.X'
```
--------------------------------
### Search with Facets
Source: https://context7.com/meilisearch/meilisearch-java/llms.txt
Enable faceting to categorize search results based on specified attributes. The facet distribution can be retrieved from the search results.
```java
// Search with facets
SearchRequest request = SearchRequest.builder()
.q("adventure")
.facets(new String[]{"genres", "release_year"})
.build();
SearchResult results = (SearchResult) index.search(request);
Object facetDistribution = results.getFacetDistribution();
```
--------------------------------
### Export Secret GPG Key
Source: https://github.com/meilisearch/meilisearch-java/blob/main/CONTRIBUTING.md
Export your secret GPG key in an armored format to a file named signing-key.asc for backup or transfer.
```bash
gpg --armor --export-secret-keys $KEY_ID > signing-key.asc
```
--------------------------------
### Add, Update, Retrieve, and Delete Documents in Meilisearch Java SDK
Source: https://context7.com/meilisearch/meilisearch-java/llms.txt
Use these methods to manage documents within an index. Operations are asynchronous and return TaskInfo. Ensure you wait for tasks to complete for subsequent operations.
```java
import com.meilisearch.sdk.Index;
import com.meilisearch.sdk.model.TaskInfo;
import com.meilisearch.sdk.model.Results;
import com.meilisearch.sdk.model.DocumentsQuery;
Index index = client.index("movies");
// Add documents from JSON string
String 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\"]}" +
"]";
TaskInfo task = index.addDocuments(documents);
index.waitForTask(task.getTaskUid());
// Add documents with explicit primary key
TaskInfo task = index.addDocuments(documents, "id");
// Add documents in batches (useful for large datasets)
TaskInfo[] tasks = index.addDocumentsInBatches(documents, 1000, "id");
for (TaskInfo t : tasks) {
index.waitForTask(t.getTaskUid());
}
// Update documents (partial update)
String updates = "[{\"id\": \"1\", \"title\": \"Carol (2015)\"}]";
TaskInfo task = index.updateDocuments(updates);
// Get a single document by ID
Movie movie = index.getDocument("1", Movie.class);
// Get a single document as raw JSON
String rawDoc = index.getRawDocument("1");
// Get multiple documents with query parameters
DocumentsQuery query = new DocumentsQuery()
.setLimit(10)
.setOffset(0)
.setFields(new String[]{"id", "title", "genres"});
Results results = index.getDocuments(query, Movie.class);
// Delete a single document
TaskInfo task = index.deleteDocument("1");
// Delete documents by filter (requires filterable attributes)
TaskInfo task = index.deleteDocumentsByFilter("genres = Drama");
// Delete all documents
TaskInfo task = index.deleteAllDocuments();
```
--------------------------------
### Decode GPG Key
Source: https://github.com/meilisearch/meilisearch-java/blob/main/CONTRIBUTING.md
Decode the GPG secret key from a base64 encoded string stored in an environment variable into a binary file named secring.gpg.
```bash
base64 -d $SIGNING_SECRET_KEY_RING_FILE > secring.gpg
```
--------------------------------
### Perform a search with filters
Source: https://github.com/meilisearch/meilisearch-java/blob/main/README.md
Configures filterable attributes and executes a filtered search query. Note that updating filterable attributes triggers an index rebuild.
```java
index.updateFilterableAttributesSettings(new String[]
{
"id",
"genres"
});
```
```java
index.search(
new SearchRequest("wonder")
.setFilter(new String[] {"id > 1 AND genres = Action"})
);
```
```json
{
"hits": [
{
"id": 2,
"title": "Wonder Woman",
"genres": ["Action","Adventure"]
}
],
"offset": 0,
"limit": 20,
"estimatedTotalHits": 1,
"processingTimeMs": 0,
"query": "wonder"
}
```
--------------------------------
### Execute Multi-Search Queries
Source: https://context7.com/meilisearch/meilisearch-java/llms.txt
Perform multiple search queries across different indexes in a single request. Supports both standard multi-search and federated results.
```java
import com.meilisearch.sdk.MultiSearchRequest;
import com.meilisearch.sdk.IndexSearchRequest;
import com.meilisearch.sdk.MultiSearchFederation;
import com.meilisearch.sdk.model.Results;
import com.meilisearch.sdk.model.MultiSearchResult;
// Create multi-search request
MultiSearchRequest multiSearch = new MultiSearchRequest();
// Add queries for different indexes
IndexSearchRequest moviesQuery = new IndexSearchRequest("movies")
.setQuery("adventure")
.setLimit(5);
multiSearch.addQuery(moviesQuery);
IndexSearchRequest booksQuery = new IndexSearchRequest("books")
.setQuery("adventure")
.setLimit(5);
multiSearch.addQuery(booksQuery);
// Execute multi-search
Results results = client.multiSearch(multiSearch);
// Federated multi-search (combines results from multiple indexes)
MultiSearchFederation federation = new MultiSearchFederation();
federation.setLimit(10);
federation.setOffset(0);
MultiSearchResult federatedResult = client.multiSearch(multiSearch, federation);
```
--------------------------------
### Show Match Positions in Results
Source: https://context7.com/meilisearch/meilisearch-java/llms.txt
Enable the display of match positions within the search results. This can be useful for understanding where query terms appear in the documents.
```java
// Show match positions in results
SearchRequest request = SearchRequest.builder()
.q("adventure")
.showMatchesPosition(true)
.build();
```
--------------------------------
### Manage API Keys in Java
Source: https://context7.com/meilisearch/meilisearch-java/llms.txt
Perform CRUD operations on API keys to control access permissions and index restrictions.
```java
import com.meilisearch.sdk.model.Key;
import com.meilisearch.sdk.model.KeyUpdate;
import com.meilisearch.sdk.model.Results;
import java.util.Date;
// List all API keys
Results keys = client.getKeys();
for (Key key : keys.getResults()) {
System.out.println("Key: " + key.getKey());
System.out.println("Name: " + key.getName());
System.out.println("Actions: " + String.join(", ", key.getActions()));
}
// Get a specific key by UID
Key key = client.getKey("key-uid-here");
// Create a new API key
Key newKey = new Key();
newKey.setName("Search Only Key");
newKey.setDescription("Key for search operations only");
newKey.setActions(new String[]{"search"});
newKey.setIndexes(new String[]{"movies", "books"});
newKey.setExpiresAt(new Date(System.currentTimeMillis() + 86400000)); // Expires in 24 hours
Key createdKey = client.createKey(newKey);
System.out.println("Created key: " + createdKey.getKey());
// Create key with all permissions
Key adminKey = new Key();
adminKey.setName("Admin Key");
adminKey.setActions(new String[]{"*"});
adminKey.setIndexes(new String[]{"*"});
adminKey.setExpiresAt(null); // Never expires
Key createdAdminKey = client.createKey(adminKey);
// Update a key
KeyUpdate update = new KeyUpdate();
update.setName("Updated Key Name");
update.setDescription("Updated description");
Key updatedKey = client.updateKey(createdKey.getKey(), update);
// Delete a key
client.deleteKey(createdKey.getKey());
```
--------------------------------
### Search with Specific Attributes to Retrieve
Source: https://context7.com/meilisearch/meilisearch-java/llms.txt
Limit the returned fields in search results to only those specified. This can improve performance by reducing the amount of data transferred.
```java
// Search with specific attributes to retrieve
SearchRequest request = SearchRequest.builder()
.q("adventure")
.attributesToRetrieve(new String[]{"id", "title", "genres"})
.build();
```
--------------------------------
### Search with Cropping
Source: https://context7.com/meilisearch/meilisearch-java/llms.txt
Implement text cropping for long attributes to limit the displayed content. Define attributes to crop, the length, and the marker for truncated text.
```java
// Search with cropping
SearchRequest request = SearchRequest.builder()
.q("adventure")
.attributesToCrop(new String[]{"overview"})
.cropLength(50)
.cropMarker("...")
.build();
```
--------------------------------
### Perform a custom search
Source: https://github.com/meilisearch/meilisearch-java/blob/main/README.md
Uses SearchRequest to configure advanced search options like highlighting and match positions.
```java
import com.meilisearch.sdk.SearchRequest;
// ...
SearchResult results = (SearchResult) index.search(
new SearchRequest("of")
.setShowMatchesPosition(true)
.setAttributesToHighlight(new String[]{"title"})
);
System.out.println(results.getHits());
```
```json
[{
"id":3,
"title":"Life of Pi",
"genres":["Adventure","Drama"],
"_formatted":{
"id":3,
"title":"Life of Pi",
"genres":["Adventure","Drama"]
},
"_matchesPosition":{
"title":[{
"start":5.0,
"length":2.0
}]
}
}]
```
--------------------------------
### Add documents to an index
Source: https://github.com/meilisearch/meilisearch-java/blob/main/README.md
Adds a collection of documents to a specified index. If the index does not exist, it is created automatically.
```java
package com.meilisearch.sdk;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
class TestMeilisearch {
public static void main(String[] args) throws Exception {
JSONArray array = new JSONArray();
ArrayList items = new ArrayList() {{
add(new JSONObject().put("id", "1").put("title", "Carol").put("genres",new JSONArray("[\"Romance\",\"Drama\"]")));
add(new JSONObject().put("id", "2").put("title", "Wonder Woman").put("genres",new JSONArray("[\"Action\",\"Adventure\"]")));
add(new JSONObject().put("id", "3").put("title", "Life of Pi").put("genres",new JSONArray("[\"Adventure\",\"Drama\"]")));
add(new JSONObject().put("id", "4").put("title", "Mad Max: Fury Road").put("genres",new JSONArray("[\"Adventure\",\"Science Fiction\"]")));
add(new JSONObject().put("id", "5").put("title", "Moana").put("genres",new JSONArray("[\"Fantasy\",\"Action\"]")));
add(new JSONObject().put("id", "6").put("title", "Philadelphia").put("genres",new JSONArray("[\"Drama\"]")));
}};
array.put(items);
String documents = array.getJSONArray(0).toString();
Client client = new Client(new Config("http://localhost:7700", "masterKey"));
// An index is where the documents are stored.
Index index = client.index("movies");
// If the index 'movies' does not exist, Meilisearch creates it when you first add the documents.
index.addDocuments(documents); // => { "taskUid": 0 }
}
}
```
--------------------------------
### Search with Sorting
Source: https://context7.com/meilisearch/meilisearch-java/llms.txt
Control the order of search results by specifying sorting criteria. You can sort by multiple attributes in ascending or descending order.
```java
// Search with sorting
SearchRequest request = SearchRequest.builder()
.q("adventure")
.sort(new String[]{"release_year:desc", "title:asc"})
.build();
```
--------------------------------
### Search with Filters
Source: https://context7.com/meilisearch/meilisearch-java/llms.txt
Apply filters to narrow down search results based on specific criteria. Ensure filterable attributes are configured in your Meilisearch index settings.
```java
// Search with filters (requires filterable attributes configured)
SearchRequest request = SearchRequest.builder()
.q("adventure")
.filter(new String[]{"genres = Action", "release_year > 2000"})
.build();
```
--------------------------------
### Implement Custom JsonHandler
Source: https://github.com/meilisearch/meilisearch-java/blob/main/README.md
Define a custom JSON handler by implementing the required encode and decode methods.
```java
String encode(Object o) throws Exception;
T decode(Object o, Class> targetClass, Class>... parameters) throws Exception;
```
--------------------------------
### Manage Asynchronous Tasks in Java
Source: https://context7.com/meilisearch/meilisearch-java/llms.txt
Monitor, filter, cancel, and delete background tasks. Note that all write operations in Meilisearch are asynchronous.
```java
import com.meilisearch.sdk.model.Task;
import com.meilisearch.sdk.model.TaskInfo;
import com.meilisearch.sdk.model.TasksResults;
import com.meilisearch.sdk.model.TasksQuery;
import com.meilisearch.sdk.model.CancelTasksQuery;
import com.meilisearch.sdk.model.DeleteTasksQuery;
// Get task info after an operation
TaskInfo taskInfo = index.addDocuments(documents);
int taskUid = taskInfo.getTaskUid();
// Wait for task to complete (default timeout)
index.waitForTask(taskUid);
// Wait with custom timeout and polling interval (in milliseconds)
index.waitForTask(taskUid, 30000, 100); // 30s timeout, 100ms interval
// Check task status manually
Task task = client.getTask(taskUid);
System.out.println("Status: " + task.getStatus()); // enqueued, processing, succeeded, failed, canceled
System.out.println("Type: " + task.getType());
System.out.println("Duration: " + task.getDuration());
if (task.getError() != null) {
System.out.println("Error: " + task.getError().getMessage());
}
// Get all tasks
TasksResults allTasks = client.getTasks();
// Get tasks with filters
TasksQuery query = new TasksQuery()
.setIndexUids(new String[]{"movies"})
.setStatuses(new String[]{"failed", "canceled"})
.setTypes(new String[]{"documentAdditionOrUpdate"})
.setLimit(10);
TasksResults filteredTasks = client.getTasks(query);
// Cancel enqueued or processing tasks
CancelTasksQuery cancelQuery = new CancelTasksQuery()
.setIndexUids(new String[]{"movies"})
.setStatuses(new String[]{"enqueued"});
TaskInfo cancelTask = client.cancelTasks(cancelQuery);
// Delete finished tasks
DeleteTasksQuery deleteQuery = new DeleteTasksQuery()
.setStatuses(new String[]{"succeeded", "failed"});
TaskInfo deleteTask = client.deleteTasks(deleteQuery);
// Get tasks for a specific index
TasksResults indexTasks = index.getTasks();
```
--------------------------------
### Manage Meilisearch Indexes
Source: https://context7.com/meilisearch/meilisearch-java/llms.txt
Perform CRUD operations on indexes and handle atomic index swaps.
```java
import com.meilisearch.sdk.Client;
import com.meilisearch.sdk.Config;
import com.meilisearch.sdk.Index;
import com.meilisearch.sdk.model.TaskInfo;
import com.meilisearch.sdk.model.Results;
Client client = new Client(new Config("http://localhost:7700", "masterKey"));
// Create an index without primary key (auto-detected on first document addition)
TaskInfo task = client.createIndex("movies");
// Create an index with a specified primary key
TaskInfo task = client.createIndex("movies", "id");
// Get a local reference to an index (no HTTP call)
Index index = client.index("movies");
// Fetch an index from the server
Index index = client.getIndex("movies");
// List all indexes
Results indexes = client.getIndexes();
for (Index idx : indexes.getResults()) {
System.out.println("Index: " + idx.getUid() + ", Primary Key: " + idx.getPrimaryKey());
}
// Update index primary key
TaskInfo task = client.updateIndex("movies", "movie_id");
// Delete an index
TaskInfo task = client.deleteIndex("movies");
// Swap indexes (atomically exchange documents and settings)
SwapIndexesParams[] swaps = new SwapIndexesParams[]{
new SwapIndexesParams(new String[]{"movies", "movies_new"})
};
TaskInfo task = client.swapIndexes(swaps);
```
--------------------------------
### Update Version in build.gradle
Source: https://github.com/meilisearch/meilisearch-java/blob/main/CONTRIBUTING.md
Update the version property in the build.gradle file to match the new release version.
```gradle
version = 'X.X.X'
```
--------------------------------
### Perform Hybrid Search
Source: https://context7.com/meilisearch/meilisearch-java/llms.txt
Execute a hybrid search query by combining keyword and semantic search. Configure the semantic ratio and the embedder to use.
```java
// Perform hybrid search
Hybrid hybrid = Hybrid.builder()
.semanticRatio(0.5) // 0 = pure keyword, 1 = pure semantic
.embedder("openai")
.build();
SearchRequest request = SearchRequest.builder()
.q("feel-good movies about friendship")
.hybrid(hybrid)
.build();
Searchable results = index.search(request);
```
--------------------------------
### Perform a paginated search
Source: https://github.com/meilisearch/meilisearch-java/blob/main/README.md
Retrieves search results using pagination parameters.
```java
import com.meilisearch.sdk.SearchResultPaginated;
// ...
SearchResultPaginated results = (SearchResultPaginated) index.search(
new SearchRequest("wonder")
.setPage(1)
.setHitsPerPage(20)
);
```
```json
{
"hits": [
{
"id": 2,
"title": "Wonder Woman",
"genres": ["Action","Adventure"]
}
],
"query": "wonder",
"processingTimeMs": 0,
"hitsPerPage": 20,
"page": 1,
"totalPages": 1,
"totalHits": 1
}
```
--------------------------------
### Handle Meilisearch SDK Errors
Source: https://context7.com/meilisearch/meilisearch-java/llms.txt
Catch specific Meilisearch exceptions like `MeilisearchApiException`, `MeilisearchCommunicationException`, and `MeilisearchTimeoutException` for granular error handling. Also, check task statuses for failures.
```java
import com.meilisearch.sdk.exceptions.MeilisearchException;
import com.meilisearch.sdk.exceptions.MeilisearchApiException;
import com.meilisearch.sdk.exceptions.MeilisearchCommunicationException;
import com.meilisearch.sdk.exceptions.MeilisearchTimeoutException;
try {
Index index = client.getIndex("nonexistent");
} catch (MeilisearchApiException e) {
// API returned an error response
System.out.println("API Error: " + e.getMessage());
System.out.println("Error Code: " + e.getCode());
System.out.println("Error Type: " + e.getType());
System.out.println("HTTP Status: " + e.getStatusCode());
} catch (MeilisearchCommunicationException e) {
// Network or connection error
System.out.println("Connection failed: " + e.getMessage());
} catch (MeilisearchTimeoutException e) {
// Operation timed out
System.out.println("Timeout: " + e.getMessage());
} catch (MeilisearchException e) {
// General Meilisearch error
System.out.println("Error: " + e.getMessage());
}
// Handling task failures
try {
TaskInfo taskInfo = index.addDocuments(invalidDocuments);
index.waitForTask(taskInfo.getTaskUid());
Task task = client.getTask(taskInfo.getTaskUid());
if (task.getStatus().equals("failed")) {
System.out.println("Task failed: " + task.getError().getMessage());
System.out.println("Error code: " + task.getError().getCode());
}
} catch (MeilisearchException e) {
System.out.println("Error: " + e.getMessage());
}
```
--------------------------------
### Search Similar Documents
Source: https://context7.com/meilisearch/meilisearch-java/llms.txt
Find documents semantically similar to a specific document ID. Requires configured embedders.
```java
import com.meilisearch.sdk.SimilarDocumentRequest;
import com.meilisearch.sdk.model.SimilarDocumentsResults;
Index index = client.index("movies");
// Search for documents similar to a specific document
SimilarDocumentRequest request = new SimilarDocumentRequest()
.setId("movie_123") // Document ID to find similar documents for
.setEmbedder("openai") // Embedder to use
.setLimit(10)
.setOffset(0);
SimilarDocumentsResults results = index.searchSimilarDocuments(request);
```
--------------------------------
### Webhook Management API
Source: https://context7.com/meilisearch/meilisearch-java/llms.txt
Endpoints for listing, retrieving, creating, updating, and deleting webhooks to notify external services of task completion.
```APIDOC
## Webhooks
### Description
Manage webhooks to receive notifications when tasks are completed.
### Methods
- GET /webhooks (List all)
- GET /webhooks/{webhookUid} (Get specific)
- POST /webhooks (Create)
- PUT /webhooks/{webhookUid} (Update)
- DELETE /webhooks/{webhookUid} (Delete)
### Request Body (Create/Update)
- **url** (string) - Required - The URL to receive task completion events.
- **headers** (Map) - Optional - Custom headers for the webhook request.
```
--------------------------------
### Search with Ranking Score
Source: https://context7.com/meilisearch/meilisearch-java/llms.txt
Include ranking scores in the search results and filter results based on a ranking score threshold. This provides insight into result relevance.
```java
// Search with ranking score
SearchRequest request = SearchRequest.builder()
.q("adventure")
.showRankingScore(true)
.showRankingScoreDetails(true)
.rankingScoreThreshold(0.5)
.build();
```
--------------------------------
### Update Version in Version.java
Source: https://github.com/meilisearch/meilisearch-java/blob/main/CONTRIBUTING.md
Modify the VERSION constant in Version.java to reflect the new release version.
```java
VERSION = "X.X.X";
```
--------------------------------
### Search on Specific Attributes Only
Source: https://context7.com/meilisearch/meilisearch-java/llms.txt
Restrict the search query to only consider specified attributes. This is useful for targeted searches where you know which fields are most relevant.
```java
// Search on specific attributes only
SearchRequest request = SearchRequest.builder()
.q("space")
.attributesToSearchOn(new String[]{"title", "overview"})
.build();
```
--------------------------------
### Retrieve Vectors in Search Results
Source: https://context7.com/meilisearch/meilisearch-java/llms.txt
Optionally retrieve vectors in search results. This can be useful for debugging or further analysis of the semantic search component.
```java
// Retrieve vectors in search results
SearchRequest request = SearchRequest.builder()
.q("adventure")
.retrieveVectors(true)
.build();
```
--------------------------------
### Perform Facet Search
Source: https://context7.com/meilisearch/meilisearch-java/llms.txt
Search for specific facet values within a faceted attribute. Requires the attribute to be configured as filterable.
```java
import com.meilisearch.sdk.FacetSearchRequest;
import com.meilisearch.sdk.model.FacetSearchable;
import com.meilisearch.sdk.model.FacetSearchResult;
Index index = client.index("movies");
// First, ensure the attribute is filterable
index.updateFilterableAttributesSettings(new String[]{"genres", "release_year"});
// Search for facet values
FacetSearchRequest request = new FacetSearchRequest("genres")
.setFacetQuery("act") // Search for genres containing "act" (e.g., "Action")
.setQuery("adventure"); // Optional: limit to documents matching this query
FacetSearchable results = index.facetSearch(request);
// With filters
FacetSearchRequest request = new FacetSearchRequest("genres")
.setFacetQuery("dra")
.setFilter(new String[]{"release_year > 2010"});
// Get raw JSON response
String rawResults = index.rawFacetSearch(request);
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.