Skip to content

Repository files navigation

Typesense Java Client ☕ 🔍

Java client library for accessing the HTTP API of Typesense search engine.

Installation

The client is available on Maven central:

dependencies {
implementation 'org.typesense:typesense-java:1.3.0'
}
<dependency>
<groupId>org.typesense</groupId>
<artifactId>typesense-java</artifactId>
<version>1.3.0</version>
</dependency>
importorg.typesense.api.*;
importorg.typesense.model.*;
importorg.typesense.resources.*;

Compatibility

typesense-java is compatible with Java versions 8+ and Android SDK versions 26+

Usage

Create a new client

List<Node> nodes = newArrayList<>();
nodes.add(
newNode(
"http", // For Typesense Cloud use https"localhost", // For Typesense Cloud use xxx.a1.typesense.net"8108"// For Typesense Cloud use 443
)
);
Configurationconfiguration = newConfiguration(nodes, Duration.ofSeconds(2),"<API_KEY>");
Clientclient = newClient(configuration);

Create a new collection

List<Field> fields = newArrayList<>();
fields.add(newField().name("countryName").type(FieldTypes.STRING));
fields.add(newField().name("capital").type(FieldTypes.STRING));
fields.add(newField().name("gdp").type(FieldTypes.INT32).facet(true).sort(true));
CollectionSchemacollectionSchema = newCollectionSchema();
collectionSchema.name("Countries").fields(fields).defaultSortingField("gdp");
client.collections().create(collectionSchema);

Create a new collection from JSON file

StringschemaJson = newString(
Files.readAllBytes(Paths.get("schema.json")),
StandardCharsets.UTF_8
);
client.collections().create(schemaJson);

Index a document

Map<String, Object> hmap = newHashMap<>();
hmap.put("countryName","India");
hmap.put("capital","Delhi");
hmap.put("gdp", 10);
client.collections("Countries").documents().create(hmap);

Upserting a document

Map<String, Object> hmap = newHashMap<>();
hmap.put("countryName","India");
hmap.put("capital","Delhi");
hmap.put("gdp", 5);
client.collections("Countries").documents().upsert(hmap);

Import batch of documents

ImportDocumentsParametersqueryParameters = newImportDocumentsParameters();
queryParameters.action("create");
StringdocumentList = "{\"countryName\": \"India\", \"capital\": \"Washington\", \"gdp\": 5215}\n" +
"{\"countryName\": \"Iran\", \"capital\": \"London\", \"gdp\": 5215}";
// Import your document as JSONL string from a file.client.collections("Countries").documents().import_(documentList, queryParameters)

Search in a collection

SearchParameterssearchParameters = newSearchParameters()
.q("tokoyo")
.queryBy("countryName,capital")
.prefix("true,false");
SearchResultsearchResult = client.collections("Countries").documents().search(searchParameters);

Update a document

Map<String, Object> hmap = newHashMap<>();
hmap.put("gdp", 8);
client.collections("Countries").documents("28").update(hmap);

Retrieve a document

client.collections("Countries").documents("28").retrieve();

Delete a document

client.collections("Countries").documents("28").delete();

Delete documents using query

DeleteDocumentsParametersdeleteDocumentsParameters = newDeleteDocumentsParameters();
deleteDocumentsParameters.filterBy("gdp:=[2,8]");
deleteDocumentsParameters.batchSize(10);

Retrieve a collection

client.collections("Countries").retrieve();

Retrieve all collections

client.collections().retrieve();

Drop a collection

client.collections("Countries").delete(); 

Export a collection

client.collections("Countries").documents().export();

Create an analytics rule

AnalyticsRuleSchemaanalyticsRule = newAnalyticsRuleSchema();
analyticsRule.setName("popular-queries");
analyticsRule.setType(AnalyticsRuleSchema.TypeEnum.POPULAR_QUERIES);
analyticsRule.setParams(newAnalyticsRuleParameters()
.source(newAnalyticsRuleParametersSource()
.collections(Arrays.asList("Countries")))
.destination(newAnalyticsRuleParametersDestination()
.collection("top_searches")));
client.analytics().rules().create(analyticsRule);

Upsert an analytics rule

AnalyticsRuleUpsertSchemaanalyticsRule = newAnalyticsRuleUpsertSchema()
.type(AnalyticsRuleUpsertSchema.TypeEnum.NOHITS_QUERIES)
.params(newAnalyticsRuleParameters()
.source(newAnalyticsRuleParametersSource()
.collections(Arrays.asList("Countries")))
.destination(newAnalyticsRuleParametersDestination()
.collection("failed_searches")));
client.analytics().rules().upsert("failed-searches", analyticsRule);

Retrieve all analytics rules

AnalyticsRulesRetrieveSchemarules = client.analytics().rules().retrieve();

Retrieve a single analytics rule

AnalyticsRuleSchemarule = client.analytics().rules("failed-searches").retrieve();

Delete an analytics rule

client.analytics().rules("failed-searches").delete();

Create an analytics event

AnalyticsEventCreateSchemaanalyticsEvent = newAnalyticsEventCreateSchema()
.type("conversion")
.name("purchase_made")
.data(Map.of(
"product_id", "123",
"user_id", "user_456",
"amount", "99.99"
));
client.analytics().events().create(analyticsEvent);

Upsert a stopwords set

List<String> stopwords = newArrayList<>();
stopwords.add("the");
stopwords.add("of");
stopwords.add("and");
StopwordsSetUpsertSchemastopwordsSet = newStopwordsSetUpsertSchema();
stopwordsSet.stopwords(stopwords);
client.stopwords().upsert("common-words", stopwordsSet);

Retrieve a stopwords set

StopwordsSetRetrieveSchemaset = client.stopwords("common-words").retrieve();

Retrieve all stopwords sets

StopwordsSetsRetrieveAllSchemasets = client.stopwords().retrieve();

Delete a stopwords set

client.stopwords("common-words").delete();

Create an API key

ApiKeySchemaapiKeySchema = newApiKeySchema();
List<String> actionValues = newArrayList<>();
List<String> collectionValues = newArrayList<>();
actionValues.add("*");
collectionValues.add("*");
apiKeySchema.description("Admin Key").actions(actionValues).collections(collectionValues);
client.keys().create(apiKeySchema);

Create search only API key

ApiKeySchemaapiKeySchema = newApiKeySchema();
List<String> actionValues = newArrayList<>();
List<String> collectionValues = newArrayList<>();
actionValues.add("documents:search");
collectionValues.add("Countries");
apiKeySchema.description("Search only Key").actions(actionValues).collections(collectionValues);
client.keys().create(apiKeySchema);

Retrieve an API key

client.keys("6").retrieve();

List all the API keys

client.keys().retrieve();

Delete an API keys

client.keys("6").delete();

Create or update an override

SearchOverrideSchemasearchOverrideSchema = newSearchOverrideSchema();
List<SearchOverrideInclude> searchOverrideIncludes = newArrayList<>();
searchOverrideIncludes.add(newSearchOverrideInclude().id("422").position(1));
searchOverrideIncludes.add(newSearchOverrideInclude().id("54").position(2));
List<SearchOverrideExclude> searchOverrideExcludes = newArrayList<>();
searchOverrideExcludes.add(newSearchOverrideExclude().id("287"));
searchOverrideSchema.rule(newSearchOverrideRule().query("new york").match("exact"))
.includes(searchOverrideIncludes)
.excludes(searchOverrideExcludes);
client.collections("Countries").overrides().upsert("new-york", searchOverrideSchema)

Retrieve an Alias

client.collections("Countries").overrides("new-york").retrieve();

List all overrides

client.collections("Countries").overrides().retrieve();

Delete an override

client.collections("Countries").overrides("new-york").delete();

Upsert an Alias

CollectionAliasSchemacollectionAliasSchema = newCollectionAliasSchema();
collectionAliasSchema.collectionName("Countries");
client.aliases().upsert("countries2", collectionAliasSchema)

Retrieve an Alias

client.aliases("countries2").retrieve();

List all Aliases

client.aliases().retrieve();

Delete an Alias

client.aliases("countries2").delete();

Upsert a multi-way synonym

SearchSynonymSchemasynonym = newSearchSynonymSchema();
synonym.addSynonymsItem("France").addSynonymsItem("Germany").addSynonymsItem("Sweden");
client.collections("Countries").synonyms().upsert("country-synonyms",synonym)

Upsert a single-way synonym

SearchSynonymSchemasynonym = newSearchSynonymSchema();
synonym.root("europe");
synonym.addSynonymsItem("France").addSynonymsItem("Germany").addSynonymsItem("Sweden");
client.collections("Countries").synonyms().upsert("continent-synonyms",synonym)

Retrieve a synonym

client.collections("Countries").synonyms("continent-synonyms").retrieve();

Retrieve all synonyms

client.collections("Countries").synonyms().retrieve();

Delete a synonym

client.collections("Countries").synonyms("continent-synonyms").delete();

Create snapshot (for backups)

Map<String, String> query = newHashMap<>();
query.put("snapshot_path","/tmp/typesense-data-snapshot");
client.operations.perform("snapshot",query);

Re-elect Leader

client.operations.perform("vote");

Check health

client.health.retrieve();

Contributing

Please read CONTRIBUTING.md for details on the process for submitting pull requests to this repository.

License

typesense-java is distributed under the Apache 2 license.

Support

Please open a Github issue or join our Slack Community

Releases

Sponsor this project

Used by

Contributors

Languages