GithubHelp home page GithubHelp logo

algolia / algoliasearch-client-csharp Goto Github PK

View Code? Open in Web Editor NEW
118.0 81.0 61.0 5.13 MB

⚡️ A fully-featured and blazing-fast C# API client to interact with Algolia.

Home Page: https://www.algolia.com/doc/api-client/getting-started/install/csharp/

License: MIT License

C# 99.99% Dockerfile 0.01%
c-sharp algolia algolia-search api-client dotnet dotnet-core dotnet-standard csharp search-engine dotnet-library

algoliasearch-client-csharp's Introduction

Algolia for C#

The perfect starting point to integrate Algolia within your .NET project

Nuget CircleCI Licence

DocumentationCommunity ForumStack OverflowReport a bugFAQSupport

✨ Features

  • Targets .NET Standard:
    • .NET Standard 1.3 to .NET Standard 2.1.
    • For more details about supported .NET implementations, please see .NET Standard official page.
  • Asynchronous and synchronous methods to interact with Algolia's API
  • Thread-safe clients
  • Typed requests and responses
  • Injectable HTTP client

Migration note from v5.x to v6.x

In January 2019, we released v6 of our .NET client. If you are using version 5.x of the client, read the migration guide to version 6.x. Version 5.x will no longer be under active development.

💡 Getting Started

Install the library with the .NET CLI:

dotnet add package Algolia.Search

or with the Nuget Package Manager Console:

Install-Package Algolia.Search

In 30 seconds, this quick start tutorial will show you how to index and search objects.

Initialize the cient

To start, you need to initialize the client. To do this, you need your Application ID and API Key. You can find both on your Algolia account.

SearchClient client = new SearchClient("YourApplicationID", "YourAPIKey");
SearchIndex index = client.InitIndex("your_index_name");

Push data

Without any prior configuration, you can start indexing contacts in the contacts index using the following code:

public class Contact
{
  public string ObjectID { get; set; }
  public string Name { get; set; }
  public int Age { get; set; }
}

SearchIndex index = client.InitIndex("contacts");

index.SaveObject(new Contact
{
    ObjectID = "ID1",
    Name = "Jimmie",
    Age = 30
});

Search

You can now search for contacts by firstname, lastname, company, etc. (even with typos):

// Synchronous
index.Search<Contact>(new Query { "jimmie" });

// Asynchronous
await index.SearchAsync<Contact>(new Query { "jimmie" });

For full documentation, visit the Algolia .NET API Client documentation.

ASP.NET

If you're using ASP.NET, checkout the following tutorial.

❓ Troubleshooting

Encountering an issue? Before reaching out to support, we recommend heading to our FAQ where you will find answers for the most common issues and gotchas with the client.

Use the Dockerfile

If you want to contribute to this project without installing all its dependencies, you can use our Docker image. Please check our dedicated guide to learn more.

📄 License

Algolia .NET API Client is an open-sourced software licensed under the MIT license.

algoliasearch-client-csharp's People

Contributors

algolia-bot avatar algoliareadmebot avatar ant-hem avatar aseure avatar azure-pipelines[bot] avatar beamop avatar cbaptiste avatar chrismckee avatar dessaigne avatar dethi avatar devincodes avatar ehayman avatar haroenv avatar hugohallqvist avatar julienbourdeau avatar morganleroi avatar nunomaduro avatar peppage avatar pixelastic avatar redox avatar renovate[bot] avatar robertmogos avatar sarahdayan avatar sbellone avatar scottksmith95 avatar sebastianstehle avatar shipow avatar speedblue avatar spinach avatar tomklotzpro avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

algoliasearch-client-csharp's Issues

PartialUpdateObjects

Not so far to method 'PartialUpdateObject' was added argument 'createIfNotExists'. That allows user not to add some partial information to algolia when for some reason full object was not stored to index.

For me most likely case to partially update batch of objects. That's why it would be greate to add the same parameter to 'PartialUpdateObjects' method:
PartialUpdateObjects(batch, bool createIfNotExists = true).
And, of course, to it async clone.

SaveSynonym should use `forwardToReplicas` instead of `forwardToSlaves`

Following our internal renaming initiative, the SaveSynonym method should have a few minor adjustements. The REST API now accepts forwardToReplicas in addition to forwardToSlaves when adding synonyms. All the documentation is being updated so it mentions forwardToReplicas.

The C# client should send forwardToReplicas instead of forwardToSlaves. Internal variables could also be renamed.

DeleteObject is not deleting the entry after migrating to 6.0.0

  • Algolia Client Version: 6.0.0
  • Language Version: C# 6.0

Description

Hi,
We are using the following code to delete an object from Algolia
index.DeleteObject(ObjectID);

However, it's not deleting the entry after upgrading to version 6.0.0

Steps To Reproduce

Error on the DeleteByQueryAsync method when Distinct > 1

In the case the distinct is enabled on an index (with distinct > 1), a call to the method DeleteByQueryAsync returns the following error:

{
  "message": "invalid distinct value, hitsPerPage * distinct should be <= 1000",
  "status": 400
}

We should probably override distinct=false at query time when the method performs the search call.

Azure functions fail with Index functions

IDE: Visual Studio 2017 Preview
Framework 4.6.2/4.7/others
Project: Azure functions
Trigger Servicebus
Error: method not found:

Implementation Code:

  public static class PostBlogSearch
    {
        [FunctionName("CreateBlogSearch")]
        public static void Run([ServiceBusTrigger("PostBlog", "Search", AccessRights.Manage, Connection = "ServiceBus")]PostBlogModel myQueueItem, TraceWriter log)
        {
            var searchBarItem = new SearchBarItem()
            {
                objectID = myQueueItem.Id,
                ImageUrl = myQueueItem.ImageUrl,
                Rating = 100,
                Text = myQueueItem.Text.Substring(0, Math.Min(myQueueItem.Text.Length, 80)),
                Title = myQueueItem.Title,
                Keywords = "Blog Nieuws " + myQueueItem.Text,
                Type = "Blog"
            };
            dynamic index = DefaultClients.AlgoliaClient.InitIndex(myQueueItem.PlatformId.ToString());
            var obj = JObject.FromObject(searchBarItem);
            var list=new List<JObject> { obj };
            index.SaveObjects(list); //ERROR LINE
            log.Info($"C# ServiceBus queue trigger function processed message: {myQueueItem}");
        }
    }

Console when not dynamic (hitpoints wont be hit)


[16-8-2017 12:34:57] Function completed (Failure, Id=47a300d8-7b80-48a1-a29e-6298259aa01c, Duration=10ms)
[16-8-2017 12:34:57]
[16-8-2017 12:34:57] Executed 'CreateBlogSearch' (Failed, Id=47a300d8-7b80-48a1-a29e-6298259aa01c)
[16-8-2017 12:34:57] mscorlib: Exception while executing function: CreateBlogSearch. FunctionsProject: Methode niet gevonden: Newtonsoft.Json.Linq.JObject Algolia.Search.Index.SaveObjects(System.Collections.Generic.IEnumerable`1<Newtonsoft.Json.Linq.JObject>).
[16-8-2017 12:34:57]   Function had errors. See Azure WebJobs SDK dashboard for details. Instance ID is '47a300d8-7b80-48a1-a29e-6298259aa01c'
[16-8-2017 12:34:57] mscorlib: Exception while executing function: CreateBlogSearch. FunctionsProject: Methode niet gevonden: Newtonsoft.Json.Linq.JObject Algolia.Search.Index.SaveObjects(System.Collections.Generic.IEnumerable`1<Newtonsoft.Json.Linq.JObject>).

StackTrace when dynamic:

   bij Microsoft.CSharp.RuntimeBinder.RuntimeBinder.Bind(DynamicMetaObjectBinder payload, IEnumerable`1 parameters, DynamicMetaObject[] args, DynamicMetaObject& deferredBinding)
   bij Microsoft.CSharp.RuntimeBinder.BinderHelper.Bind(DynamicMetaObjectBinder action, RuntimeBinder binder, IEnumerable`1 args, IEnumerable`1 arginfos, DynamicMetaObject onBindingError)
   bij Microsoft.CSharp.RuntimeBinder.CSharpInvokeMemberBinder.FallbackInvokeMember(DynamicMetaObject target, DynamicMetaObject[] args, DynamicMetaObject errorSuggestion)
   bij System.Dynamic.DynamicMetaObject.BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args)
   bij System.Dynamic.InvokeMemberBinder.Bind(DynamicMetaObject target, DynamicMetaObject[] args)
   bij System.Dynamic.DynamicMetaObjectBinder.Bind(Object[] args, ReadOnlyCollection`1 parameters, LabelTarget returnLabel)
   bij System.Runtime.CompilerServices.CallSiteBinder.BindCore[T](CallSite`1 site, Object[] args)
   bij System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid2[T0,T1](CallSite site, T0 arg0, T1 arg1)
   bij FunctionsProject.publicSearchbar.PostBlogSearch.Run(PostBlogModel myQueueItem, TraceWriter log)
   bij lambda_method(Closure , PostBlogSearch , Object[] )
   bij Microsoft.Azure.WebJobs.Host.Executors.VoidMethodInvoker`2.InvokeAsync(TReflected instance, Object[] arguments)
   bij Microsoft.Azure.WebJobs.Host.Executors.FunctionInvoker`2.<InvokeAsync>d__8.MoveNext()

Analytics API

Are you going to be extending this client to support the Analytics API?

BrowseAll Usage

I'm trying to use the Browse method with a pager in a SEO purpose.

I call the BrowseAll method with a query containing a facetfilter and a page number.
All works fine until I reach the last page.

Here is my code:
`var query = new Query()
.SetNbHitsPerPage(settings.PageSize)
.SetPage(settings.PageIndex);

// set query facetfilter

var it = index.BrowseAll(query);
int countFromOffset = it.Count(); // Throws an Exception if query asks the last incomplete page

var result = new BrowseResult
{
PageIndex = settings.PageIndex,
PageSize = settings.PageSize,
};
result.TotalCount = result.PageIndex * result.PageSize + countFromOffset;
result.PageCount = result.TotalCount / result.PageSize;
if (result.PageCount * result.PageSize < result.TotalCount)
result.PageCount++;

result.Items = it.Take(result.PageSize)
.Select(item => item.ToObject())
.ToList();`

The full result of BrowsAll contains 1080 items and each of our pages contains 48 items.
So there are 23 pages to display and the last one should only contains 24 items.

If query page is set to 22 (the last page), parsing the iterator throws the AgloliaException :
you should pass cursor of current page to fetch next page

Is it a bug or a wrong usage ?
Thanks for your help

Secured API keys not working

When I use this code in code behind

algoliaSettings.PublicKey = client.GenerateSecuredApiKey(algoliaSettings.SearchApiKey, newQuery().EnableAnalytics(true));

it will work.

But when I use this it will not

algoliaSettings.PublicKey = client.GenerateSecuredApiKey(algoliaSettings.SearchApiKey, newQuery().SetFilters("filter:myFilter").AddCustomParameter("validUntil", unix));

AddExtraQueryParameters should be able to take an array of values

Description

[JsonPropertyAttribute("objectID")] not working correctly

We hit a similar bug to Issue #536 , but we're not using a base class with our POCO. The following decoration results in the exception: "The type T must have an ObjectID property or a JsonPropertyAttribute with name='objectID'"

        [JsonPropertyAttribute("objectID")]
        public string ObjectId { get; set; } 

I've reviewed the code, and can't figure out why this always fails:

if (typeInfo.GetCustomAttribute() != null)

Logs by date

It will be very usefull to retrieve index logs not by pages but by date ranges, let's say
since DateTime1 to DateTime2
Please add such method to index.

TaskCanceledException: A task was canceled.

I'm not sure if this even is an issue or if its intended behavior. But i see in our error logs that get some exceptions like this on.

File "Microsoft.Runtime.CompilerServices.TaskAwaiter" line 49 in ThrowForNonSuccess(System.Threading.Tasks.Task task)

File "Microsoft.Runtime.CompilerServices.TaskAwaiter" line 28 in HandleNonSuccess(System.Threading.Tasks.Task task)

File "Microsoft.Runtime.CompilerServices.TaskAwaiter`1" line 0 in GetResult

File "Algolia.Search.Index" line 16 in SearchDisjunctiveFaceting(Algolia.Search.Query query, System.Collections.Generic.IEnumerable`1[System.String] disjunctiveFacets, System.Collections.Generic.Dictionary`2[System.String,System.Collections.Generic.IEnumerable`1[System.String]] refinements)

File "AlternativeTo.Web.Repository.BrowseRepository" line 165 in BrowseCategory(AlternativeTo.Db.Model.Types.TagCategory category, System.Int32 page, System.String platform, System.String license, AlternativeTo.Web.Code.Types.OrderAlternatives sort, System.Int32 pageSize, System.Boolean showAdsenseBlockedItems)

It seems to only occur for bots (like googlebot, yahoo slurp and so on). It's of course hard to reproduce since it doesn't happen that often. Maybe i could just wrap this in a try catch and ignore it?

Allow sub-second timeouts

Currently the timeouts are Integers of seconds. If a customer has strict latency restrictions with a global timeout of let's say 1 second, we need sub-second timeout to fit into this budget with the retry.

Improve performance when in Unity environment

For Algolians, refer to this for more details.

Basically, In a Unity environment, using HttpClient is pretty slow and potentially needs to be changed with the a "unity" http client for better performance

FacetFilters serialization doesn't work

According to the docs, the string format for FacetFilters is something like "field:value". When the client builds its url (which seems off since the JS client posts the query) it uses JsonConvert.SerializeObject(this.FacetFilters) creating a URL string like &FacetFilters=%22field:Value%22 which is an invalid url (the colon) and doesn't match the syntax the service seems to need. There is also a method that takes an IEnumerable of strings but that does even odder things like facetFilters=%22System.String[],0,-1%22. Since filtering based on facets seems like a core function of the service, this appears to be a big issue with this client..

Logs

Please add functionality that will provide user with index 'Logs'.
I suppose it should be 'index' method with signature like:
index.GetLogs(pageNumber = 0, logsPerPage = 1000) - exactly like 'Browse' method.

index.BrowseFrom(...) result

Hello,

I'm using the nuget package Algolia.Search 3.6.5 and Newtonsoft.Json 9.0.1

index.BrowseFrom(query, cursor) returns a JObject containing only the following fields :

  • cursor
  • hits
  • params
  • processingTimeMS
  • query

If I make a CURL request, I see more data like :

  • nbHits
  • page
  • nbPages
  • hitsPerPage
  • query

How can I get these fileds ?
It would be nice to have a complete JObject result.

I need to know how many pages are returned to build a pager for SEO purpose.

No sources or changelog for Algolia.Search 5.0.0

Steps:

  1. Open the NuGet package manager
  2. Search for Algolia.Search. Observe that version 5.0.0 is available
  3. Inspect this repository

Expected results:

  • Updated sources are there
  • A 5.0 release exists
  • The ChangeLog is updated up to 5.0

Actual results: none of the above.

(Perhaps an oversight?)

Issue generating Secure API Key with SetRestrictIndices

Hi,

I'm not sure if this is a bug or by design.
When trying to create a secure API key I would get an 'Null object reference' error.

var restrictIndices = new List<String>();            
restrictIndices.Add("index-name");

var filters = new Query().SetFilters($"field={someID}").SetRestrictIndices(restrictIndices);

String publicKey = client.GenerateSecuredApiKey(settings.APIKEY, filters);

I solved it by stepping through and seeing that GetQueryString was throwing the error when it was setting the Indices:

foreach (string attr in this.facets)

this.facets was null and throwing the error.

I altered my query to include facets filter and it worked.

string[] facets = { "*" };

var filters = new Query().SetFilters($"field={someID}").SetFacets(facets).SetRestrictIndices(restrictIndices);

If you need more detail just let me know.

Thanks

Cannot install package on VS2017

Install-Package : Could not install package 'Algolia.Search 4.0.0'. You are trying to install this package into a project that targets '.NETFramework,Version=v4.0', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author .

I tried every supported framework in the README.md file, but still no luck in installing the package.

Interface for AlgoliaClient and Index?

Would be nice if these classes implemented an interface so we could mock them in unit tests. I'm happy to define one based on the current implementation and send a PR if it has any hope of getting approved.

Deserialization change in newest v.6 client

We've just run our integration process with the new v6 client.

Our index attributes are now all suddenly camelCase which has broken our configuration.

PromotedName is now promotedName

Can you please investigate?

image

GenerateSecuredApiKey method is not implemented

Current implementation:
public Task GenerateSecuredApiKey(String privateApiKey, String tagFilter, String userToken = null)
{
return null;
}

Please implement or throw an Exception if that is not possible.

The Index.SaveObject(pocoModel) dont work when ObjectId is in baseclass of POCO

The Index.SaveObject(pocoModel) dont work when ObjectId is in baseclass of POCO.
==> You get error: The type {nameof(T)} must have an ObjectID property or a JsonPropertyAttribute with name='objectID.

The issue is your AlgoliaHelper.PropertyOrJsonAttributeExists() function is wrong.
The reflection it uses to check for public properties is incorrect/wrong:

var typeInfo = typeof(T).GetTypeInfo();
var declaredProperties = typeInfo.DeclaredProperties; <=== !!!! this is wrong. !!!!!!!!

the DeclaredProperties will not retrieve the baseclass properties.
==> this is why it is not seeing ObjectID ==> because ObjectID is in base class.

The fix is to use this code:

var declaredProperties = typeof(T).GetProperties();

==> this will give you all the public properties (even the one in the base class..)

Please apply this fix asap. We are trying to use your 6.0.0 version in production as soon as possible.
Thank you.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.