Skip to content

Commit 5dd667b

Browse files
authored
chore(guides): some missing snippets + guides (#4477)
1 parent 2daecac commit 5dd667b

File tree

138 files changed

+2661
-1165
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

138 files changed

+2661
-1165
lines changed

clients/algoliasearch-client-python/algoliasearch/http/base_config.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ def __init__(self, app_id: Optional[str] = None, api_key: Optional[str] = None):
2424
self.connect_timeout = 2000
2525

2626
self.wait_task_time_before_retry: Optional[int] = None
27-
self.headers: Optional[Dict[str, str]] = None
27+
self.headers: Dict[str, str] = {}
2828
self.proxies: Optional[Dict[str, str]] = None
2929
self.hosts: Optional[HostsCollection] = None
3030

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

4038
def add_user_agent(self, segment: str, version: Optional[str] = None) -> None:
4139
"""adds a segment to the default user agent, and update the headers sent with each requests as well"""
4240
self._user_agent = self._user_agent.add(segment, version)
43-
44-
if self.headers is not None:
45-
self.headers["user-agent"] = self._user_agent.get()
41+
self.headers["user-agent"] = self._user_agent.get()

clients/algoliasearch-client-python/algoliasearch/http/request_options.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ def merge(
6969
query_parameters = {}
7070
if headers is None:
7171
headers = {}
72-
headers.update(self._config.headers or {})
72+
headers.update(self._config.headers)
7373

7474
request_options = {
7575
"headers": headers,

templates/csharp/guides/search/deleteMultipleIndices.mustache

Lines changed: 25 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -13,35 +13,31 @@ class DeleteMultipleIndices {
1313
{
1414
1515
// You need an API key with `deleteIndex`
16-
try {
17-
{{> snippets/init}}
18-
19-
// List all indices
20-
var indices = {{#dynamicSnippet}}listIndicesSimple{{/dynamicSnippet}};
21-
22-
// Primary indices don't have a `primary` key
23-
var primaryIndices = indices.Items.Where(item => item.Primary == null).ToList();
24-
var replicaIndices = indices.Items.Where(item => item.Primary != null).ToList();
25-
26-
// Delete primary indices first
27-
if (primaryIndices.Count > 0)
28-
{
29-
var requests = primaryIndices
30-
.Select(index => new MultipleBatchRequest(Search.Models.Search.Action.Delete, index.Name)).ToList();
31-
{{#dynamicSnippet}}deleteMultipleIndicesPrimary{{/dynamicSnippet}};
32-
Console.WriteLine("Deleted primary indices.");
33-
}
34-
35-
// Now, delete replica indices
36-
if (replicaIndices.Count > 0)
37-
{
38-
var requests = replicaIndices
39-
.Select(index => new MultipleBatchRequest(Search.Models.Search.Action.Delete, index.Name)).ToList();
40-
{{#dynamicSnippet}}deleteMultipleIndicesReplica{{/dynamicSnippet}};
41-
Console.WriteLine("Deleted replica indices.");
42-
}
43-
} catch (Exception e) {
44-
Console.WriteLine(e.Message);
16+
{{> snippets/init}}
17+
18+
// List all indices
19+
var indices = {{#dynamicSnippet}}listIndicesSimple{{/dynamicSnippet}};
20+
21+
// Primary indices don't have a `primary` key
22+
var primaryIndices = indices.Items.Where(item => item.Primary == null).ToList();
23+
var replicaIndices = indices.Items.Where(item => item.Primary != null).ToList();
24+
25+
// Delete primary indices first
26+
if (primaryIndices.Count > 0)
27+
{
28+
var requests = primaryIndices
29+
.Select(index => new MultipleBatchRequest(Search.Models.Search.Action.Delete, index.Name)).ToList();
30+
{{#dynamicSnippet}}deleteMultipleIndicesPrimary{{/dynamicSnippet}};
31+
Console.WriteLine("Deleted primary indices.");
32+
}
33+
34+
// Now, delete replica indices
35+
if (replicaIndices.Count > 0)
36+
{
37+
var requests = replicaIndices
38+
.Select(index => new MultipleBatchRequest(Search.Models.Search.Action.Delete, index.Name)).ToList();
39+
{{#dynamicSnippet}}deleteMultipleIndicesReplica{{/dynamicSnippet}};
40+
Console.WriteLine("Deleted replica indices.");
4541
}
4642
}
4743
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
namespace Algolia;
2+
3+
using System;
4+
using System.Text.Json;
5+
using System.Net.Http;
6+
using System.Collections.Generic;
7+
8+
{{> snippets/import}}
9+
10+
class GlobalAlgoliaUserID
11+
{
12+
async Task Main(string[] args)
13+
{
14+
var client = new SearchClient(
15+
new SearchConfig("ALGOLIA_APPLICATION_ID", "ALGOLIA_API_KEY")
16+
{
17+
DefaultHeaders = new Dictionary<string, string> { { "X-Algolia-UserToken", "test-user-123" } }
18+
}
19+
);
20+
Console.WriteLine(client);
21+
}
22+
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
namespace Algolia;
2+
3+
using System;
4+
using System.Text.Json;
5+
using System.Net.Http;
6+
using System.Collections.Generic;
7+
8+
{{> snippets/import}}
9+
10+
class McmSearchWithout {
11+
12+
private static string GetAppIdFor(string user) {
13+
return ""; // Implement your own logic here
14+
}
15+
16+
private static string GetIndexingApiKeyFor(string user) {
17+
return ""; // Implement your own logic here
18+
}
19+
20+
async Task Main(string[] args)
21+
{
22+
23+
// Fetch from your own data storage and with your own code
24+
// the associated application ID and API key for this user
25+
var appId = GetAppIdFor("user42");
26+
var apiKey = GetIndexingApiKeyFor("user42");
27+
28+
var client = new SearchClient(new SearchConfig(appId, apiKey));
29+
var searchParams = new SearchParams(new SearchParamsObject
30+
{
31+
Query = "<YOUR_SEARCH_QUERY>",
32+
FacetFilters = new FacetFilters([new FacetFilters("user:user42"), new FacetFilters("user:public")])
33+
}
34+
);
35+
36+
{{#dynamicSnippet}}searchWithSearchParams{{/dynamicSnippet}};
37+
}
38+
}
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
namespace Algolia;
2+
3+
using System;
4+
using System.Text.Json;
5+
using System.Net.Http;
6+
using System.Collections.Generic;
7+
8+
{{> snippets/import}}
9+
10+
class SaveImageClassifications {
11+
12+
class Image
13+
{
14+
public required string ImageUrl { get; set; }
15+
public required string ObjectId { get; set; }
16+
public required List<Dictionary<string, object>> Objects { get; set; }
17+
}
18+
19+
// Retrieve labels
20+
async Task<Image> GetImageLabels(string imageURL, string objectID, float scoreLimit)
21+
{
22+
// Implement your image classification logic here
23+
return await Task.Run(() => new Image
24+
{
25+
ImageUrl = "",
26+
ObjectId = "",
27+
Objects = []
28+
});
29+
}
30+
31+
async Task Main(string[] args)
32+
{
33+
34+
try {
35+
// API key ACL should include editSettings / addObject
36+
{{> snippets/init}}
37+
38+
var hits = await client.BrowseObjectsAsync<Image>(
39+
"<YOUR_INDEX_NAME>",
40+
new BrowseParamsObject()
41+
);
42+
43+
var records = hits
44+
.Select(hit => GetImageLabels(hit.ImageUrl, hit.ObjectId, 0.5f))
45+
.Select(src => src.Result)
46+
.ToList();
47+
48+
// Update records with image classifications
49+
{{#dynamicSnippet}}partialUpdatesRecords{{/dynamicSnippet}};
50+
} catch (Exception e) {
51+
Console.WriteLine(e.Message);
52+
}
53+
}
54+
}
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
namespace Algolia;
2+
3+
using System;
4+
using System.Text.Json;
5+
using System.Net.Http;
6+
using System.Collections.Generic;
7+
8+
{{> snippets/import}}
9+
10+
class SaveImageClassificationsAndSettings {
11+
12+
class Image
13+
{
14+
public required string ImageUrl { get; set; }
15+
public required string ObjectId { get; set; }
16+
public required List<Dictionary<string, object>> Objects { get; set; }
17+
}
18+
19+
// Retrieve labels
20+
async Task<Image> GetImageLabels(string imageURL, string objectID, float scoreLimit)
21+
{
22+
// Implement your image classification logic here
23+
return await Task.Run(() => new Image
24+
{
25+
ImageUrl = "",
26+
ObjectId = "",
27+
Objects = []
28+
});
29+
}
30+
31+
async Task Main(string[] args)
32+
{
33+
34+
try {
35+
// API key ACL should include editSettings / addObject
36+
{{> snippets/init}}
37+
38+
var hits = await client.BrowseObjectsAsync<Image>(
39+
"<YOUR_INDEX_NAME>",
40+
new BrowseParamsObject()
41+
);
42+
43+
var images = hits.ToList();
44+
var records = images
45+
.Select(hit => GetImageLabels(hit.ImageUrl, hit.ObjectId, 0.5f))
46+
.Select(src => src.Result)
47+
.ToList();
48+
49+
// Update records with image classifications
50+
{{#dynamicSnippet}}partialUpdatesRecords{{/dynamicSnippet}};
51+
52+
List<string> facets = [];
53+
List<string> attributes = [];
54+
55+
foreach (var image in images)
56+
{
57+
foreach (var obj in image.Objects)
58+
{
59+
foreach (var key in obj.Keys)
60+
{
61+
if (obj[key] is IEnumerable<object>)
62+
{
63+
facets.Add($"searchable(objects.{key}.label)");
64+
facets.Add($"searchable(objects.{key}.score)");
65+
attributes.Add($"objects.{key}.label");
66+
}
67+
}
68+
}
69+
}
70+
71+
var currentSettings = {{#dynamicSnippet}}getSettings{{/dynamicSnippet}};
72+
73+
var settings = new IndexSettings
74+
{
75+
SearchableAttributes = currentSettings.SearchableAttributes.Concat(attributes).ToList(),
76+
AttributesForFaceting = currentSettings.AttributesForFaceting.Concat(facets).ToList()
77+
};
78+
79+
{{#dynamicSnippet}}setSettings{{/dynamicSnippet}};
80+
} catch (Exception e) {
81+
Console.WriteLine(e.Message);
82+
}
83+
}
84+
}

templates/csharp/guides/search/saveObjectsChunks.mustache

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -12,20 +12,20 @@ class SaveObjectsChunks {
1212
async Task Main(string[] args)
1313
{
1414
15-
try {
16-
{{> snippets/init}}
17-
var jsonContent = await File.ReadAllTextAsync("actors.json");
18-
var records = JsonSerializer.Deserialize<List<Dictionary<string, object>>>(jsonContent);
15+
{{> snippets/init}}
16+
var jsonContent = await File.ReadAllTextAsync("actors.json");
17+
var records = JsonSerializer.Deserialize<List<Dictionary<string, object>>>(jsonContent);
1918

20-
const int chunkSize = 10000;
19+
const int chunkSize = 10000;
2120

22-
for (var beginIndex = 0; beginIndex < records?.Count; beginIndex += chunkSize)
23-
{
21+
for (var beginIndex = 0; beginIndex < records?.Count; beginIndex += chunkSize)
22+
{
23+
try {
2424
var chunk = records.Slice(beginIndex, Math.Min(beginIndex + chunkSize, records.Count));
2525
{{#dynamicSnippet}}saveObjectsChunks{{/dynamicSnippet}};
26+
} catch (Exception e) {
27+
Console.WriteLine(e.Message);
2628
}
27-
} catch (Exception e) {
28-
Console.WriteLine(e.Message);
2929
}
3030
}
3131
}

templates/csharp/guides/search/saveObjectsModified.mustache

Lines changed: 19 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -12,31 +12,27 @@ class SaveObjectsModified {
1212
async Task Main(string[] args)
1313
{
1414
15-
try {
16-
{{> snippets/init}}
15+
{{> snippets/init}}
1716

18-
var jsonContent = await File.ReadAllTextAsync("products.json");
19-
var products = JsonSerializer.Deserialize<List<Dictionary<string, object>>>(jsonContent);
17+
var jsonContent = await File.ReadAllTextAsync("products.json");
18+
var products = JsonSerializer.Deserialize<List<Dictionary<string, object>>>(jsonContent);
2019

21-
var records = products?.Select(product =>
20+
var records = products?.Select(product =>
21+
{
22+
var reference = product.GetValueOrDefault("product_reference", "") as string;
23+
var suffixes = new List<string>();
24+
25+
for (var i = reference!.Length; i > 1; i--)
26+
{
27+
suffixes.Add(reference[i..]);
28+
}
29+
30+
return new Dictionary<string, object>(product)
2231
{
23-
var reference = product.GetValueOrDefault("product_reference", "") as string;
24-
var suffixes = new List<string>();
25-
26-
for (var i = reference!.Length; i > 1; i--)
27-
{
28-
suffixes.Add(reference[i..]);
29-
}
30-
31-
return new Dictionary<string, object>(product)
32-
{
33-
["suffixes"] = suffixes
34-
};
35-
}).ToList();
36-
37-
{{#dynamicSnippet}}saveObjectsRecords{{/dynamicSnippet}};
38-
} catch (Exception e) {
39-
Console.WriteLine(e.Message);
40-
}
32+
["suffixes"] = suffixes
33+
};
34+
}).ToList();
35+
36+
{{#dynamicSnippet}}saveObjectsRecords{{/dynamicSnippet}};
4137
}
4238
}

templates/csharp/guides/search/saveObjectsPublicUser.mustache

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,7 @@ class SaveObjectsPublicUser {
1414
async Task Main(string[] args)
1515
{
1616
17-
try {
18-
{{> snippets/init}}
19-
{{#dynamicSnippet}}saveObjectsPlaylistsWithUserIDPublic{{/dynamicSnippet}};
20-
} catch (Exception e) {
21-
Console.WriteLine(e.Message);
22-
}
17+
{{> snippets/init}}
18+
{{#dynamicSnippet}}saveObjectsPlaylistsWithUserIDPublic{{/dynamicSnippet}};
2319
}
2420
}

0 commit comments

Comments
 (0)