Search code examples
asp.net-coreelasticsearch.net-corenest

Elasticsearch NEST - System.StackOverflowException when running Index


When I run this code:

var result = _client.Index<EntityType>(item, i => i.Index(n));

I'm getting this error:

Exception has occurred: CLR/System.StackOverflowException An unhandled exception of type 'System.StackOverflowException' occurred in Elasticsearch.Net.dll

The full method:

public bool Index<EntityType>(EntityType item, int attempt = 0) where EntityType : class, IDomainEntity<int>
{
    const int maxRetries = 5;
    if (item == null)
    {
        return false;
    }
    var type = item.GetType();
    var attributes = type.CustomAttributes;
    string n = "";

    foreach (var attribute in attributes)
    {
        foreach (var arg in attribute.NamedArguments)
        {
            if (arg.MemberName == "RelationName")
            {
                n = arg.TypedValue.Value.ToString().ToLower();
            }
        }
    }

    var result = _client.Index<EntityType>(item, i => i.Index(n));
    if (!CheckResponse(result) && attempt < maxRetries)
    {
        RefreshClient<EntityType>();
        attempt++;
        return Index(item, attempt);
    }
    RefreshClient<EntityType>();
    return result.IsValid;
}

Solution

  • I added [PropertyName("propertyToIgnoreInElasticsearch", Ignore = true)] from NEST to my POCO fields which were causing an infinite loop while Indexing. It ignores a field from the Elasticsearch Index so it is not indexed.

    for example:

    [Serializable]
    public abstract class VeganItem<VeganItemEstablishmentType>
    {
        [Required]
        public string Name { get; set; }
    
        [PropertyName("veganItemEstablishments", Ignore = true)]
        public virtual ICollection<VeganItemEstablishmentType> VeganItemEstablishments { get; set; }
    }