Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ def __init__(self, app_id: Optional[str] = None, api_key: Optional[str] = None):
self.connect_timeout = 2000

self.wait_task_time_before_retry: Optional[int] = None
self.headers: Optional[Dict[str, str]] = None
self.headers: Dict[str, str] = {}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why this change ?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because ultimately we always use it as a dict, it's never treated like it can be None
So setting it to an empty dict from the beginning ease the DX

self.proxies: Optional[Dict[str, str]] = None
self.hosts: Optional[HostsCollection] = None

Expand All @@ -33,13 +33,9 @@ def __init__(self, app_id: Optional[str] = None, api_key: Optional[str] = None):
def set_client_api_key(self, api_key: str) -> None:
"""Sets a new API key to authenticate requests."""
self.api_key = api_key
if self.headers is None:
self.headers = {}
self.headers["x-algolia-api-key"] = api_key

def add_user_agent(self, segment: str, version: Optional[str] = None) -> None:
"""adds a segment to the default user agent, and update the headers sent with each requests as well"""
self._user_agent = self._user_agent.add(segment, version)

if self.headers is not None:
self.headers["user-agent"] = self._user_agent.get()
self.headers["user-agent"] = self._user_agent.get()
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ def merge(
query_parameters = {}
if headers is None:
headers = {}
headers.update(self._config.headers or {})
headers.update(self._config.headers)

request_options = {
"headers": headers,
Expand Down
54 changes: 25 additions & 29 deletions templates/csharp/guides/search/deleteMultipleIndices.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -13,35 +13,31 @@ class DeleteMultipleIndices {
{

// You need an API key with `deleteIndex`
try {
{{> snippets/init}}

// List all indices
var indices = {{#dynamicSnippet}}listIndicesSimple{{/dynamicSnippet}};

// Primary indices don't have a `primary` key
var primaryIndices = indices.Items.Where(item => item.Primary == null).ToList();
var replicaIndices = indices.Items.Where(item => item.Primary != null).ToList();

// Delete primary indices first
if (primaryIndices.Count > 0)
{
var requests = primaryIndices
.Select(index => new MultipleBatchRequest(Search.Models.Search.Action.Delete, index.Name)).ToList();
{{#dynamicSnippet}}deleteMultipleIndicesPrimary{{/dynamicSnippet}};
Console.WriteLine("Deleted primary indices.");
}

// Now, delete replica indices
if (replicaIndices.Count > 0)
{
var requests = replicaIndices
.Select(index => new MultipleBatchRequest(Search.Models.Search.Action.Delete, index.Name)).ToList();
{{#dynamicSnippet}}deleteMultipleIndicesReplica{{/dynamicSnippet}};
Console.WriteLine("Deleted replica indices.");
}
} catch (Exception e) {
Console.WriteLine(e.Message);
{{> snippets/init}}

// List all indices
var indices = {{#dynamicSnippet}}listIndicesSimple{{/dynamicSnippet}};

// Primary indices don't have a `primary` key
var primaryIndices = indices.Items.Where(item => item.Primary == null).ToList();
var replicaIndices = indices.Items.Where(item => item.Primary != null).ToList();

// Delete primary indices first
if (primaryIndices.Count > 0)
{
var requests = primaryIndices
.Select(index => new MultipleBatchRequest(Search.Models.Search.Action.Delete, index.Name)).ToList();
{{#dynamicSnippet}}deleteMultipleIndicesPrimary{{/dynamicSnippet}};
Console.WriteLine("Deleted primary indices.");
}

// Now, delete replica indices
if (replicaIndices.Count > 0)
{
var requests = replicaIndices
.Select(index => new MultipleBatchRequest(Search.Models.Search.Action.Delete, index.Name)).ToList();
{{#dynamicSnippet}}deleteMultipleIndicesReplica{{/dynamicSnippet}};
Console.WriteLine("Deleted replica indices.");
}
}
}
22 changes: 22 additions & 0 deletions templates/csharp/guides/search/globalAlgoliaUserID.mustache
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
namespace Algolia;

using System;
using System.Text.Json;
using System.Net.Http;
using System.Collections.Generic;

{{> snippets/import}}

class GlobalAlgoliaUserID
{
async Task Main(string[] args)
{
var client = new SearchClient(
new SearchConfig("ALGOLIA_APPLICATION_ID", "ALGOLIA_API_KEY")
{
DefaultHeaders = new Dictionary<string, string> { { "X-Algolia-UserToken", "test-user-123" } }
}
);
Console.WriteLine(client);
}
}
38 changes: 38 additions & 0 deletions templates/csharp/guides/search/mcmSearchWithout.mustache
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
namespace Algolia;

using System;
using System.Text.Json;
using System.Net.Http;
using System.Collections.Generic;

{{> snippets/import}}

class McmSearchWithout {

private static string GetAppIdFor(string user) {
return ""; // Implement your own logic here
}

private static string GetIndexingApiKeyFor(string user) {
return ""; // Implement your own logic here
}

async Task Main(string[] args)
{

// Fetch from your own data storage and with your own code
// the associated application ID and API key for this user
var appId = GetAppIdFor("user42");
var apiKey = GetIndexingApiKeyFor("user42");

var client = new SearchClient(new SearchConfig(appId, apiKey));
var searchParams = new SearchParams(new SearchParamsObject
{
Query = "<YOUR_SEARCH_QUERY>",
FacetFilters = new FacetFilters([new FacetFilters("user:user42"), new FacetFilters("user:public")])
}
);

{{#dynamicSnippet}}searchWithSearchParams{{/dynamicSnippet}};
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
namespace Algolia;

using System;
using System.Text.Json;
using System.Net.Http;
using System.Collections.Generic;

{{> snippets/import}}

class SaveImageClassifications {

class Image
{
public required string ImageUrl { get; set; }
public required string ObjectId { get; set; }
public required List<Dictionary<string, object>> Objects { get; set; }
}

// Retrieve labels
async Task<Image> GetImageLabels(string imageURL, string objectID, float scoreLimit)
{
// Implement your image classification logic here
return await Task.Run(() => new Image
{
ImageUrl = "",
ObjectId = "",
Objects = []
});
}

async Task Main(string[] args)
{

try {
// API key ACL should include editSettings / addObject
{{> snippets/init}}

var hits = await client.BrowseObjectsAsync<Image>(
"<YOUR_INDEX_NAME>",
new BrowseParamsObject()
);

var records = hits
.Select(hit => GetImageLabels(hit.ImageUrl, hit.ObjectId, 0.5f))
.Select(src => src.Result)
.ToList();

// Update records with image classifications
{{#dynamicSnippet}}partialUpdatesRecords{{/dynamicSnippet}};
} catch (Exception e) {
Console.WriteLine(e.Message);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
namespace Algolia;

using System;
using System.Text.Json;
using System.Net.Http;
using System.Collections.Generic;

{{> snippets/import}}

class SaveImageClassificationsAndSettings {

class Image
{
public required string ImageUrl { get; set; }
public required string ObjectId { get; set; }
public required List<Dictionary<string, object>> Objects { get; set; }
}

// Retrieve labels
async Task<Image> GetImageLabels(string imageURL, string objectID, float scoreLimit)
{
// Implement your image classification logic here
return await Task.Run(() => new Image
{
ImageUrl = "",
ObjectId = "",
Objects = []
});
}

async Task Main(string[] args)
{

try {
// API key ACL should include editSettings / addObject
{{> snippets/init}}

var hits = await client.BrowseObjectsAsync<Image>(
"<YOUR_INDEX_NAME>",
new BrowseParamsObject()
);

var images = hits.ToList();
var records = images
.Select(hit => GetImageLabels(hit.ImageUrl, hit.ObjectId, 0.5f))
.Select(src => src.Result)
.ToList();

// Update records with image classifications
{{#dynamicSnippet}}partialUpdatesRecords{{/dynamicSnippet}};

List<string> facets = [];
List<string> attributes = [];

foreach (var image in images)
{
foreach (var obj in image.Objects)
{
foreach (var key in obj.Keys)
{
if (obj[key] is IEnumerable<object>)
{
facets.Add($"searchable(objects.{key}.label)");
facets.Add($"searchable(objects.{key}.score)");
attributes.Add($"objects.{key}.label");
}
}
}
}

var currentSettings = {{#dynamicSnippet}}getSettings{{/dynamicSnippet}};

var settings = new IndexSettings
{
SearchableAttributes = currentSettings.SearchableAttributes.Concat(attributes).ToList(),
AttributesForFaceting = currentSettings.AttributesForFaceting.Concat(facets).ToList()
};

{{#dynamicSnippet}}setSettings{{/dynamicSnippet}};
} catch (Exception e) {
Console.WriteLine(e.Message);
}
}
}
18 changes: 9 additions & 9 deletions templates/csharp/guides/search/saveObjectsChunks.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -12,20 +12,20 @@ class SaveObjectsChunks {
async Task Main(string[] args)
{

try {
{{> snippets/init}}
var jsonContent = await File.ReadAllTextAsync("actors.json");
var records = JsonSerializer.Deserialize<List<Dictionary<string, object>>>(jsonContent);
{{> snippets/init}}
var jsonContent = await File.ReadAllTextAsync("actors.json");
var records = JsonSerializer.Deserialize<List<Dictionary<string, object>>>(jsonContent);

const int chunkSize = 10000;
const int chunkSize = 10000;

for (var beginIndex = 0; beginIndex < records?.Count; beginIndex += chunkSize)
{
for (var beginIndex = 0; beginIndex < records?.Count; beginIndex += chunkSize)
{
try {
var chunk = records.Slice(beginIndex, Math.Min(beginIndex + chunkSize, records.Count));
{{#dynamicSnippet}}saveObjectsChunks{{/dynamicSnippet}};
} catch (Exception e) {
Console.WriteLine(e.Message);
}
} catch (Exception e) {
Console.WriteLine(e.Message);
}
}
}
42 changes: 19 additions & 23 deletions templates/csharp/guides/search/saveObjectsModified.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -12,31 +12,27 @@ class SaveObjectsModified {
async Task Main(string[] args)
{

try {
{{> snippets/init}}
{{> snippets/init}}

var jsonContent = await File.ReadAllTextAsync("products.json");
var products = JsonSerializer.Deserialize<List<Dictionary<string, object>>>(jsonContent);
var jsonContent = await File.ReadAllTextAsync("products.json");
var products = JsonSerializer.Deserialize<List<Dictionary<string, object>>>(jsonContent);

var records = products?.Select(product =>
var records = products?.Select(product =>
{
var reference = product.GetValueOrDefault("product_reference", "") as string;
var suffixes = new List<string>();

for (var i = reference!.Length; i > 1; i--)
{
suffixes.Add(reference[i..]);
}

return new Dictionary<string, object>(product)
{
var reference = product.GetValueOrDefault("product_reference", "") as string;
var suffixes = new List<string>();

for (var i = reference!.Length; i > 1; i--)
{
suffixes.Add(reference[i..]);
}

return new Dictionary<string, object>(product)
{
["suffixes"] = suffixes
};
}).ToList();

{{#dynamicSnippet}}saveObjectsRecords{{/dynamicSnippet}};
} catch (Exception e) {
Console.WriteLine(e.Message);
}
["suffixes"] = suffixes
};
}).ToList();

{{#dynamicSnippet}}saveObjectsRecords{{/dynamicSnippet}};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,7 @@ class SaveObjectsPublicUser {
async Task Main(string[] args)
{

try {
{{> snippets/init}}
{{#dynamicSnippet}}saveObjectsPlaylistsWithUserIDPublic{{/dynamicSnippet}};
} catch (Exception e) {
Console.WriteLine(e.Message);
}
{{> snippets/init}}
{{#dynamicSnippet}}saveObjectsPlaylistsWithUserIDPublic{{/dynamicSnippet}};
}
}
Loading