private SolrWebRequest PrepareUpdateOrDeleteRequest <T>(T[] documentsToUpdate, object[] deleteDocIds, string deleteByQuery, bool softCommit = false)
        {
            var index = Configuration.GetIndex(typeof(T));

            if (string.IsNullOrEmpty(index))
            {
                throw new ArgumentNullException(nameof(index),
                                                string.Format(
                                                    "The type '{0}' is not assigned for any Solr Index. Register this type in a service configuration (SolrRequestConfiguration.MapIndexFor)",
                                                    typeof(T).Name));
            }

            string path    = string.Format("/{1}/{0}/update", index, string.IsNullOrEmpty(Configuration.SolrPath) ? "solr" : Configuration.SolrPath);
            var    request = new SolrWebRequest(path, SolrWebMethod.POST);

            var updateDocs = JsonConvert.SerializeObject(documentsToUpdate,
                                                         Newtonsoft.Json.Formatting.None,
                                                         new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore
            });

            request.AddParameter("wt", "json");
            request.AddParameter("commit", "true");
            if (softCommit)
            {
                request.AddParameter("softCommit", "true");
            }
            if (documentsToUpdate != null && documentsToUpdate.Any())
            {
                request.Body = updateDocs;
            }
            else if (deleteDocIds != null && deleteDocIds.Any())
            {
                request.Body = JsonConvert.SerializeObject(new { delete = deleteDocIds });
            }
            else if (!string.IsNullOrEmpty(deleteByQuery))
            {
                request.Body = JsonConvert.SerializeObject(new { delete = new { query = deleteByQuery } });
            }



            return(request);
        }
        private void FinalizeResponse(SolrWebRequest request)
        {
            var responce = Client.Execute(request);

            if (responce.StatusCode == HttpStatusCode.OK || responce.StatusCode == HttpStatusCode.NoContent)
            {
                LastResponse = new LinqToSolrResponse {
                    LastServiceUri = responce.ResponseUri
                };
                return;
            }

            if (!string.IsNullOrEmpty(responce.Content))
            {
                LastResponse = JsonConvert.DeserializeObject <LinqToSolrResponse>(responce.Content);
                LastResponse.LastServiceUri = responce.ResponseUri;
                LastResponse.Content        = responce.Content;
            }

            if (LastResponse.Error != null)
            {
                throw new Exception("Oops! SOLR Says: " + LastResponse.Error.Message);
            }
        }
        private SolrWebRequest PrepareQueryRequest(string index)
        {
            string path    = string.Format("/{1}/{0}/select", index, string.IsNullOrEmpty(Configuration.SolrPath) ? "solr": Configuration.SolrPath);
            var    request = new SolrWebRequest(path);


            request.AddParameter("q", "*");
            request.AddParameter("wt", "json");
            request.AddParameter("indent", "true");
            request.AddParameter("rows", Configuration.Take.ToString());
            request.AddParameter("start", Configuration.Start.ToString());

            if (CurrentQuery.JoinFields.Any())
            {
                foreach (var joiner in CurrentQuery.JoinFields)
                {
                    var joinCore = Configuration.GetIndex(joiner.PropertyRealType);
                    var joinstr  = string.Format("from={0} to={1} fromIndex={2}", joiner.ForeignKey, joiner.FieldKey, joinCore);
                    request.AddParameter("q", "{!join " + joinstr + "}");
                }
            }

            if (CurrentQuery.IsGroupEnabled)
            {
                request.AddParameter("group", "true");
                request.AddParameter("group.limit", Configuration.Take.ToString());
                request.AddParameter("group.offset", Configuration.Start.ToString());
                foreach (var groupField in CurrentQuery.GroupFields)
                {
                    request.AddParameter("group.field", groupField);
                }
            }


            if (CurrentQuery.Filters.Any())
            {
                foreach (var filter in CurrentQuery.Filters)
                {
                    request.AddParameter("fq", string.Format("{0}: ({1})", filter.Name,
                                                             string.Join(" OR ", filter.Values.Select(x => string.Format("\"{0}\"", x)).ToArray()
                                                                         )));
                }
            }


            if (!string.IsNullOrEmpty(CurrentQuery.FilterUrl))
            {
                foreach (var fstring in CurrentQuery.FilterUrl.Split(new[] { "&fq=" }, StringSplitOptions.None))
                {
                    if (!string.IsNullOrEmpty(fstring))
                    {
                        request.AddParameter("fq", fstring);
                    }
                }
            }

            if (CurrentQuery.Sortings.Any())
            {
                request.AddParameter("sort", string.Join(", ", CurrentQuery.Sortings.Select(x =>
                                                                                            string.Format("{0} {1}", x.Name, x.Order == SolrSortTypes.Desc ? "DESC" : "ASC")).ToArray()));
            }


            if (CurrentQuery.Facets.Any())
            {
                request.AddParameter("facet", "true");
                request.AddParameter("facet.mincount", "1");

                if (Configuration.FacetsLimit > 0)
                {
                    request.AddParameter("facet.limit", Configuration.FacetsLimit.ToString());
                }

                var ignoredFacets = CurrentQuery.FacetsToIgnore.Select(x => x.SolrName).ToList();
                foreach (var facet in CurrentQuery.Facets)
                {
                    request.AddParameter("facet.field", ignoredFacets.Any(x => x == facet.SolrName)
                        ? string.Format("{{!ex={0}}}{0}", facet.SolrName)
                        : facet.SolrName);
                }
            }

            if (CurrentQuery.Select != null)
            {
                request.AddParameter("fl", CurrentQuery.Select.GetSelectFields());
            }


            return(request);
        }
Example #4
0
        public SolrWebResponse Execute(SolrWebRequest request)
        {
            var paramStr =
                string.Join("&", request.Parameters.Select(x => string.Format("{0}={1}", x.Name, x.Value)).ToArray());

            _endpoint         = _endpoint.EndsWith("/") ? _endpoint.TrimEnd('/') : _endpoint;
            request.ActionUrl = request.ActionUrl.StartsWith("/") ? request.ActionUrl.TrimStart('/') : request.ActionUrl;
            paramStr          = string.Format("{0}/{1}?{2}", _endpoint, request.ActionUrl, paramStr.Substring(0, paramStr.Length));
            var response = new SolrWebResponse();

            response.ResponseUri = new Uri(paramStr);

#if NET40 || PORTABLE40 || PORTABLE
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(paramStr);


            if (request.Method == SolrWebMethod.GET)
            {
                using (var webResponse =
                           (HttpWebResponse)(System.Threading.Tasks.Task <WebResponse> .Factory.FromAsync(
                                                 webRequest.BeginGetResponse, webRequest.EndGetResponse, null)).Result)
                {
                    using (System.IO.Stream stream = webResponse.GetResponseStream())
                    {
                        var reader = new System.IO.StreamReader(stream, Encoding.UTF8);
                        response.Content    = reader.ReadToEnd();
                        response.StatusCode = webResponse.StatusCode;
                    }
                }
            }
            else
            {
                webRequest.Method      = "POST";
                webRequest.ContentType = "application/json";
                CurrentRequest         = request;
                var result = (HttpWebRequest)webRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), webRequest).AsyncState;
                return(response);
            }
#elif NET35
            var webRequest = (HttpWebRequest)WebRequest.Create(paramStr);


            if (request.Method == SolrWebMethod.GET)
            {
                using (var webResponse = (HttpWebResponse)webRequest.GetResponse())
                {
                    var encoding = Encoding.GetEncoding(webResponse.CharacterSet);

                    using (var responseStream = webResponse.GetResponseStream())
                    {
                        using (var reader = new System.IO.StreamReader(responseStream, encoding))
                        {
                            response.Content    = reader.ReadToEnd();
                            response.StatusCode = webResponse.StatusCode;
                        }
                    }
                }
            }
            else
            {
                webRequest.Method        = "POST";
                webRequest.ContentType   = "application/json";
                webRequest.ContentLength = request.Body.Length;
                var data = Encoding.UTF8.GetBytes(request.Body);
                using (var stream = webRequest.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }

                var webResponse = (HttpWebResponse)webRequest.GetResponse();
                response.Content    = new System.IO.StreamReader(webResponse.GetResponseStream()).ReadToEnd();
                response.StatusCode = webResponse.StatusCode;
            }
#else
            var client = new System.Net.Http.HttpClient();
            client.DefaultRequestHeaders.Accept.Add(
                new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

            if (request.Method == SolrWebMethod.GET)
            {
                var webResponse = client.GetAsync(paramStr).Result;
                response.Content    = webResponse.Content.ReadAsStringAsync().Result;
                response.StatusCode = webResponse.StatusCode;
            }
            else
            {
                var content     = new System.Net.Http.StringContent(request.Body, Encoding.UTF8, "application/json");
                var webResponse = client.PostAsync(paramStr, content).Result;
                //var webResponse = client.GetAsync(paramStr).Result;
                response.Content    = webResponse.Content.ReadAsStringAsync().Result;
                response.StatusCode = webResponse.StatusCode;
            }
#endif
            return(response);
        }