Ejemplo n.º 1
0
        private string GenerateBulkCommand <T>(IEnumerable <T> @objects)
        {
            @objects.ThrowIfNull("objects");

            var index = this.Settings.DefaultIndex;

            if (string.IsNullOrEmpty(index))
            {
                throw new NullReferenceException("Cannot infer default index for current connection.");
            }

            if (@objects.Count() == 0)
            {
                return(null);
            }

            var type     = typeof(T);
            var typeName = Inflector.MakePlural(type.Name).ToLower();

            Func <T, string> idSelector = null;
            var idProperty = type.GetProperty("Id");

            if (idProperty != null)
            {
                if (idProperty.PropertyType == typeof(int))
                {
                    idSelector = (@object) => ((int)@object.TryGetPropertyValue("Id")).ToString();
                }
                else if (idProperty.PropertyType == typeof(int?))
                {
                    idSelector = (@object) =>
                    {
                        int?val = (int?)@object.TryGetPropertyValue("Id");
                        return((val.HasValue) ? val.Value.ToString() : string.Empty);
                    }
                }
                ;
                else if (idProperty.PropertyType == typeof(string))
                {
                    idSelector = (@object) => (string)@object.TryGetPropertyValue("Id");
                }
            }

            var sb      = new StringBuilder();
            var command = "{{ \"index\" : {{ \"_index\" : \"{0}\", \"_type\" : \"{1}\", \"_id\" : \"{2}\" }} }}\n";

            //if we can't reflect id let ES create one.
            if (idSelector == null)
            {
                command = "{{ \"index\" : {{ \"_index\" : \"{0}\", \"_type\" : \"{1}\" }} }}\n".F(index, typeName);
            }

            foreach (var @object in objects)
            {
                string jsonCommand = JsonConvert.SerializeObject(@object, Formatting.None, this.SerializationSettings);
                if (idSelector == null)
                {
                    sb.Append(command);
                }
                else
                {
                    sb.Append(command.F(index, typeName, idSelector(@object)));
                }
                sb.Append(jsonCommand + "\n");
            }
            var json = sb.ToString();

            return(json);
        }