diff --git a/.gitignore b/.gitignore index 356a22f0c90..7cfbc350a51 100644 --- a/.gitignore +++ b/.gitignore @@ -7,6 +7,7 @@ *.user *.aps *.pch +*.tss *.vspscc *_i.c *_p.c diff --git a/src/HackerNews.Indexer/.gitignore b/src/HackerNews.Indexer/.gitignore deleted file mode 100644 index 74732854d52..00000000000 --- a/src/HackerNews.Indexer/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ - -*.ncrunchproject \ No newline at end of file diff --git a/src/HackerNews.Indexer/Domain/Post.cs b/src/HackerNews.Indexer/Domain/Post.cs deleted file mode 100644 index 8ef4a11d567..00000000000 --- a/src/HackerNews.Indexer/Domain/Post.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace HackerNews.Indexer.Domain -{ - public class Post - { - public int Id { get; set; } - public int ParentId { get; set; } - public string Url { get; set; } - public string Title { get; set; } - public string Text { get; set; } - //Totally unnecessary but need to have nesting going on. - public PostMetaData Meta { get; set;} - } -} diff --git a/src/HackerNews.Indexer/Domain/PostMetaData.cs b/src/HackerNews.Indexer/Domain/PostMetaData.cs deleted file mode 100644 index dcdb2525aa4..00000000000 --- a/src/HackerNews.Indexer/Domain/PostMetaData.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace HackerNews.Indexer.Domain -{ - public class PostMetaData - { - public string Username { get; set; } - public int Points { get; set; } - public int Type { get; set; } - public DateTime Created { get; set; } - public int CommentsCount { get; set; } - } -} diff --git a/src/HackerNews.Indexer/HackerNews.Indexer.csproj b/src/HackerNews.Indexer/HackerNews.Indexer.csproj deleted file mode 100644 index 1acb17c223e..00000000000 --- a/src/HackerNews.Indexer/HackerNews.Indexer.csproj +++ /dev/null @@ -1,105 +0,0 @@ - - - - Debug - x86 - 8.0.30703 - 2.0 - {E39CC264-A7B3-490D-84B2-D3016D86CD87} - Exe - Properties - HackerNews.Indexer - HackerNews.Indexer - v4.0 - Client - 512 - - - AnyCPU - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - x86 - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - true - bin\Debug\ - DEBUG;TRACE - full - AnyCPU - bin\Debug\HackerNews.Indexer.exe.CodeAnalysisLog.xml - true - GlobalSuppressions.cs - prompt - MinimumRecommendedRules.ruleset - ;d:\Program Files\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\\Rule Sets - true - ;d:\Program Files\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\FxCop\\Rules - true - - - bin\Release\ - TRACE - true - pdbonly - AnyCPU - bin\Release\HackerNews.Indexer.exe.CodeAnalysisLog.xml - true - GlobalSuppressions.cs - prompt - MinimumRecommendedRules.ruleset - ;d:\Program Files\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\\Rule Sets - true - ;d:\Program Files\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\FxCop\\Rules - true - false - - - - False - ..\..\dep\Newtonsoft.Json.5.0.4\lib\net40\Newtonsoft.Json.dll - - - - - - - - - - - - - - - - - - {072BA7DA-7B60-407D-8B6E-95E3186BE70C} - Nest - - - - - - - - \ No newline at end of file diff --git a/src/HackerNews.Indexer/HackerNews.Indexer.csproj.user b/src/HackerNews.Indexer/HackerNews.Indexer.csproj.user deleted file mode 100644 index a08bd693255..00000000000 --- a/src/HackerNews.Indexer/HackerNews.Indexer.csproj.user +++ /dev/null @@ -1,15 +0,0 @@ - - - - "d:\hn_full_11-07-2010.xml" - - - "d:\hn_full_11-07-2010.xml" - - - "d:\hn_full_11-07-2010.xml" - - - "d:\hn_full_11-07-2010.xml" - - \ No newline at end of file diff --git a/src/HackerNews.Indexer/HackerNews.Indexer.pidb b/src/HackerNews.Indexer/HackerNews.Indexer.pidb deleted file mode 100644 index 7691c7a3bac..00000000000 Binary files a/src/HackerNews.Indexer/HackerNews.Indexer.pidb and /dev/null differ diff --git a/src/HackerNews.Indexer/Program.cs b/src/HackerNews.Indexer/Program.cs deleted file mode 100644 index 5c955085374..00000000000 --- a/src/HackerNews.Indexer/Program.cs +++ /dev/null @@ -1,131 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Xml; -using HackerNews.Indexer.Domain; -using Nest; -using System.Diagnostics; -using System.Net; -using System.Threading.Tasks; -using System.Threading; - -namespace HackerNews.Indexer -{ - class Program - { - /// - /// Depends on hn_full_11-07-2010.xml which you can download from: - /// http://api.ihackernews.com/torrents/hn_full_11-07-2010.zip.torrent - /// - /// When run from debug make sure to change the default debug arguments. - /// Full filepath to hn_full_11-07-2010.xml - static void Main(string[] args) - { - var filePath = args.First(); - var elasticSettings = new ConnectionSettings(new Uri("http://ipv4.fiddler:9200")) - .SetDefaultIndex("mpdreamz") - .SetMaximumAsyncConnections(50); - var client = new ElasticClient(elasticSettings); - ConnectionStatus connectionStatus; - if (!client.TryConnect(out connectionStatus)) - { - Console.Error.WriteLine("Could not connect to {0}:\r\n{1}", - elasticSettings.Host, connectionStatus.Error.OriginalException.Message); - Console.Read(); - return; - } - - - var reader = new XmlTextReader(filePath); - Post post = new Post(); - PostMetaData meta = new PostMetaData(); - - int processed = 0, dropped = 0; - Stopwatch sw = new Stopwatch(); - sw.Start(); - var postQueue = new List(); - try - { - while (reader.Read()) - { - var name = reader.Name; - - if (reader.NodeType == XmlNodeType.Element) - { - if (name == "HackerNews") - continue; - - if (name == "ID") - post.Id = reader.ReadElementContentAsInt(); - - else if (name == "ParentID") - post.ParentId = reader.ReadElementContentAsInt(); - else if (name == "Url") - post.Url = reader.ReadElementContentAsString(); - else if (name == "Title") - post.Title = reader.ReadElementContentAsString(); - else if (name == "Text") - post.Text = reader.ReadElementContentAsString(); - else if (name == "Username") - meta.Username = reader.ReadElementContentAsString(); - else if (name == "Points") - meta.Points = reader.ReadElementContentAsInt(); - else if (name == "Type") - meta.Type = reader.ReadElementContentAsInt(); - else if (name == "Timestamp") - meta.Created = reader.ReadElementContentAsDateTime(); - else if (name == "CommentCount") - meta.CommentsCount = reader.ReadElementContentAsInt(); - } - - if (reader.NodeType == XmlNodeType.EndElement - && name == "row") - { - post.Meta = meta; - postQueue.Add(post); - if (postQueue.Count() == 1000) - { - var t = client.IndexManyAsync(postQueue); - t.ContinueWith(c => - { - var result = c.Result; - if (!result.IsValid) - dropped++; - }); - processed += postQueue.Count(); - postQueue = new List(); - - } - Console.Write("\rProcessed:{0}, Dropped:{2} in {1}", processed, sw.Elapsed, dropped); - - post = new Post(); - meta = new PostMetaData(); - } - } - if (postQueue.Count() > 0) - { - var task = client.IndexManyAsync(postQueue).ContinueWith(t => - { - var c = t.Result; - if (!c.IsValid) - Interlocked.Increment(ref dropped); - return t; - }); - Interlocked.Add(ref processed, postQueue.Count()); - postQueue = new List(); - - } - sw.Stop(); - Console.WriteLine("\nDone!", sw.Elapsed); - Console.WriteLine("{0} docs in {1} => {2} docs/s", processed, sw.Elapsed, processed / sw.Elapsed.TotalSeconds); - } - catch (Exception e) - { - Console.WriteLine(e.Message); - } - - - } - } -} diff --git a/src/HackerNews.Indexer/Properties/AssemblyInfo.cs b/src/HackerNews.Indexer/Properties/AssemblyInfo.cs deleted file mode 100644 index ef4125b76e7..00000000000 --- a/src/HackerNews.Indexer/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("HackerNews.Indexer")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Microsoft")] -[assembly: AssemblyProduct("HackerNews.Indexer")] -[assembly: AssemblyCopyright("Copyright © Microsoft 2010")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("8637ae27-4dc9-44da-9d57-33b84339e634")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/src/HackerNews.Indexer/packages.config b/src/HackerNews.Indexer/packages.config deleted file mode 100644 index 4ae01791349..00000000000 --- a/src/HackerNews.Indexer/packages.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/src/Nest.Connection.Thrift/ThriftConnection.cs b/src/Nest.Connection.Thrift/ThriftConnection.cs index 9f45eeac35c..30881468797 100644 --- a/src/Nest.Connection.Thrift/ThriftConnection.cs +++ b/src/Nest.Connection.Thrift/ThriftConnection.cs @@ -17,10 +17,12 @@ public class ThriftConnection : IConnection, IDisposable private readonly Semaphore _resourceLock; private readonly int _timeout; private readonly int _poolSize; - private bool _disposed; - + private bool _disposed; + private readonly IConnectionSettings _connectionSettings; + public ThriftConnection(IConnectionSettings connectionSettings) - { + { + this._connectionSettings = connectionSettings; this._timeout = connectionSettings.Timeout; this._poolSize = connectionSettings.MaximumAsyncConnections; @@ -261,7 +263,7 @@ private ConnectionStatus Execute(RestRequest restRequest) if (!this._resourceLock.WaitOne(this._timeout)) { var m = "Could not start the thrift operation before the timeout of " + this._timeout + "ms completed while waiting for the semaphore"; - return new ConnectionStatus(new TimeoutException(m)); + return new ConnectionStatus(this._connectionSettings, new TimeoutException(m)); } try { @@ -269,7 +271,7 @@ private ConnectionStatus Execute(RestRequest restRequest) if (!this._clients.TryDequeue(out client)) { var m = string.Format("Could dequeue a thrift client from internal socket pool of size {0}", this._poolSize); - var status = new ConnectionStatus(new Exception(m)); + var status = new ConnectionStatus(this._connectionSettings, new Exception(m)); return status; } try @@ -279,14 +281,15 @@ private ConnectionStatus Execute(RestRequest restRequest) var result = client.execute(restRequest); if (result.Status == Status.OK || result.Status == Status.CREATED || result.Status == Status.ACCEPTED) - return new ConnectionStatus(DecodeStr(result.Body)); + return new ConnectionStatus(this._connectionSettings, DecodeStr(result.Body)); else { - var connectionError = new ConnectionError(DecodeStr(result.Body), (int)result.Status) - { - ExceptionMessage = Enum.GetName(typeof (Status), result.Status) - }; - return new ConnectionStatus(connectionError); + var connectionException = new ConnectionException( + msg: Enum.GetName(typeof (Status), result.Status), + statusCode: (int)result.Status, + response: DecodeStr(result.Body) + ); + return new ConnectionStatus(this._connectionSettings, connectionException); } } catch @@ -302,7 +305,7 @@ private ConnectionStatus Execute(RestRequest restRequest) } catch (Exception e) { - return new ConnectionStatus(e); + return new ConnectionStatus(this._connectionSettings, e); } finally { diff --git a/src/Nest.Dsl.Factory/ElasticClient-Search.cs b/src/Nest.Dsl.Factory/ElasticClient-Search.cs deleted file mode 100644 index d4cd8eb06af..00000000000 --- a/src/Nest.Dsl.Factory/ElasticClient-Search.cs +++ /dev/null @@ -1,130 +0,0 @@ -using System; -using Nest.Dsl.Factory.Extensions; -using Nest.Dsl.Factory; -using System.Diagnostics; -using System.Threading.Tasks; -using Nest.Resolvers; - -namespace Nest -{ - public static class ElasticClientExtensions - { - public static IQueryResponse SearchRaw(this IElasticClient client, - string path, string query) where T : class - { - var connectionStatus = client.Connection.PostSync(path, query); - return client.ToParsedResponse>(connectionStatus); - } - - public static Task> SearchRawAsync(this IElasticClient client, - string path, string query) where T : class - { - return client.Connection.Post(path, query) - .ContinueWith(t=> client.ToParsedResponse>(t.Result) as IQueryResponse); - } - /// - /// Synchronously search using dynamic as its return type. - /// - public static IQueryResponse Search(this IElasticClient client, - SearchBuilder searchBuilder, - string index = null, - string type = null, - string routing = null, - SearchType? searchType = null) - { - var search = new SearchDescriptor(); - if (!index.IsNullOrEmpty()) - search.Index(index); - if (!type.IsNullOrEmpty()) - search.Type(type); - if (!routing.IsNullOrEmpty()) - search.Routing(routing); - if (searchType.HasValue) - search.SearchType(searchType.Value); - - var path = new PathResolver(client.Settings).GetSearchPathForDynamic(search); - var query = searchBuilder.ToString(); - - return client.SearchRaw(query, path); - } - - /// - /// Synchronously search using T as the return type - /// - public static IQueryResponse Search(this IElasticClient client, - SearchBuilder searchBuilder, - string index = null, - string type = null, - string routing = null, - SearchType? searchType = null) where T : class - { - var search = new SearchDescriptor(); - if (!index.IsNullOrEmpty()) - search.Index(index); - if (!type.IsNullOrEmpty()) - search.Type(type); - if (!routing.IsNullOrEmpty()) - search.Routing(routing); - if (searchType.HasValue) - search.SearchType(searchType.Value); - - var query = searchBuilder.ToString(); - var path = new PathResolver(client.Settings).GetSearchPathForTyped(search); - return client.SearchRaw(query, path); - } - - /// - /// Asynchronously search using dynamic as its return type. - /// - public static Task> SearchAsync(this IElasticClient client, - SearchBuilder searchBuilder, - string index = null, - string type = null, - string routing = null, - SearchType? searchType = null) - { - var search = new SearchDescriptor(); - if (!index.IsNullOrEmpty()) - search.Index(index); - if (!type.IsNullOrEmpty()) - search.Type(type); - if (!routing.IsNullOrEmpty()) - search.Routing(routing); - if (searchType.HasValue) - search.SearchType(searchType.Value); - - var path = new PathResolver(client.Settings).GetSearchPathForDynamic(search); - var query = searchBuilder.ToString(); - - return client.SearchRawAsync(query, path); - - } - - /// - /// Asynchronously search using T as the return type - /// - public static Task> SearchAsync(this IElasticClient client, - SearchBuilder searchBuilder, - string index = null, - string type = null, - string routing = null, - SearchType? searchType = null) where T : class - { - var search = new SearchDescriptor(); - if (!index.IsNullOrEmpty()) - search.Index(index); - if (!type.IsNullOrEmpty()) - search.Type(type); - if (!routing.IsNullOrEmpty()) - search.Routing(routing); - if (searchType.HasValue) - search.SearchType(searchType.Value); - - var query = searchBuilder.ToString(); - var path = new PathResolver(client.Settings).GetSearchPathForTyped(search); - - return client.SearchRawAsync(query, path); - } - - } -} \ No newline at end of file diff --git a/src/Nest.Dsl.Factory/Nest.Dsl.Factory.csproj b/src/Nest.Dsl.Factory/Nest.Dsl.Factory.csproj index 97f35f9fc97..41042ed2a5f 100644 --- a/src/Nest.Dsl.Factory/Nest.Dsl.Factory.csproj +++ b/src/Nest.Dsl.Factory/Nest.Dsl.Factory.csproj @@ -47,7 +47,6 @@ - diff --git a/src/Nest.Tests.Integration/Connection/Thrift/ThiftBugReportTests.cs b/src/Nest.Tests.Integration/Connection/Thrift/ThiftBugReportTests.cs index 9e0d320ce08..7b8810309be 100644 --- a/src/Nest.Tests.Integration/Connection/Thrift/ThiftBugReportTests.cs +++ b/src/Nest.Tests.Integration/Connection/Thrift/ThiftBugReportTests.cs @@ -14,7 +14,7 @@ public class ThiftBugReportTests : IntegrationTests [Test] public void IndexExistShouldNotThrowOn404() { - var isValidThriftConnection = this._thriftClient.IsValid; + var isValidThriftConnection = this._thriftClient.RootNodeInfo().IsValid; isValidThriftConnection.Should().BeTrue(); var unknownIndexResult = this._thriftClient.IndexExists("i-am-running-out-of-clever-index-names"); diff --git a/src/Nest.Tests.Integration/ConnectionTests.cs b/src/Nest.Tests.Integration/ConnectionTests.cs index b9851cb1320..5948aafbcd8 100644 --- a/src/Nest.Tests.Integration/ConnectionTests.cs +++ b/src/Nest.Tests.Integration/ConnectionTests.cs @@ -31,11 +31,9 @@ public void TestSettingsWithUri() [Test] public void TestConnectSuccess() { - ConnectionStatus status; - _client.TryConnect(out status); - Assert.True(_client.IsValid); - Assert.True(status.Success); - Assert.Null(status.Error); + var rootNodeInfo = _client.RootNodeInfo(); + Assert.True(rootNodeInfo.IsValid); + Assert.Null(rootNodeInfo.ConnectionStatus.Error); } [Test] public void construct_client_with_null() @@ -74,13 +72,13 @@ public void connect_to_unknown_hostname() { var settings = new ConnectionSettings(new Uri("http://youdontownthis.domain.do.you")); var client = new ElasticClient(settings); - ConnectionStatus connectionStatus; - client.TryConnect(out connectionStatus); + var result = client.RootNodeInfo(); - Assert.False(client.IsValid); - Assert.True(connectionStatus != null); - Assert.True(connectionStatus.Error.HttpStatusCode == System.Net.HttpStatusCode.BadGateway - || connectionStatus.Error.ExceptionMessage.StartsWith("The remote name could not be resolved")); + Assert.False(result.IsValid); + Assert.NotNull(result.ConnectionStatus); + + Assert.True(result.ConnectionStatus.Error.HttpStatusCode == System.Net.HttpStatusCode.BadGateway + || result.ConnectionStatus.Error.ExceptionMessage.StartsWith("The remote name could not be resolved")); }); } [Test] @@ -88,11 +86,10 @@ public void TestConnectSuccessWithUri() { var settings = new ConnectionSettings(Test.Default.Uri); var client = new ElasticClient(settings); - ConnectionStatus status; - client.TryConnect(out status); - Assert.True(client.IsValid); - Assert.True(status.Success); - Assert.Null(status.Error); + var result = client.RootNodeInfo(); + + Assert.True(result.IsValid); + Assert.Null(result.ConnectionStatus.Error); } [Test] public void construct_client_with_null_uri() diff --git a/src/Nest.Tests.Integration/Core/Map/MetaField/MetaFieldTests.cs b/src/Nest.Tests.Integration/Core/Map/MetaField/MetaFieldTests.cs index a5412713dda..cbdd9344226 100644 --- a/src/Nest.Tests.Integration/Core/Map/MetaField/MetaFieldTests.cs +++ b/src/Nest.Tests.Integration/Core/Map/MetaField/MetaFieldTests.cs @@ -14,9 +14,11 @@ public void MetaFieldSerializes() .Meta(d => d .Add("attr1", "value1") .Add("attr2", new { attr3 = "value3" }) - .Add("attr4", 10) + .Add("Attr4", 10) ) ); + //make sure Attr4 is not serialized as attr4 + StringAssert.DoesNotContain("attr4", result.ConnectionStatus.Request, result.ConnectionStatus.Request); this.DefaultResponseAssertations(result); } } diff --git a/src/Nest.Tests.Integration/Integration/Filter/MissingExistsFilterTests.cs b/src/Nest.Tests.Integration/Integration/Filter/MissingExistsFilterTests.cs index b5686997ddb..880e4fe8e12 100644 --- a/src/Nest.Tests.Integration/Integration/Filter/MissingExistsFilterTests.cs +++ b/src/Nest.Tests.Integration/Integration/Filter/MissingExistsFilterTests.cs @@ -33,8 +33,6 @@ public class MissingExistsFilterTests : IntegrationTests [TestFixtureSetUp] public void Initialize() { - _client.IsValid.Should().BeTrue(); - _LookFor = NestTestData.Session.Single().Get(); _MissingField = f => f.Name; _ExistsField = f => f.Id; diff --git a/src/Nest.Tests.Integration/Integration/Filter/RangeFilterTests.cs b/src/Nest.Tests.Integration/Integration/Filter/RangeFilterTests.cs index 49506ee0fa8..eb6f15f62a9 100644 --- a/src/Nest.Tests.Integration/Integration/Filter/RangeFilterTests.cs +++ b/src/Nest.Tests.Integration/Integration/Filter/RangeFilterTests.cs @@ -20,8 +20,6 @@ public class RangeFilterTests : IntegrationTests [TestFixtureSetUp] public void Initialize() { - _client.IsValid.Should().BeTrue(); - _LookFor = NestTestData.Session.Single().Get(); _LookFor.Name = "mmm"; var status = this._client.Index(_LookFor, new IndexParameters { Refresh = true }).ConnectionStatus; diff --git a/src/Nest.Tests.Integration/Integration/HighlightTests.cs b/src/Nest.Tests.Integration/Integration/HighlightTests.cs index 35d35cd1490..7d1180d7f1f 100644 --- a/src/Nest.Tests.Integration/Integration/HighlightTests.cs +++ b/src/Nest.Tests.Integration/Integration/HighlightTests.cs @@ -44,7 +44,7 @@ public void TestHighlight() Assert.NotNull(highlights["content"]); Assert.Greater(highlights["content"].Highlights.Count(), 0); - highlights = result.DocumentsWithMetaData.First().Highlight; + highlights = result.DocumentsWithMetaData.First().Highlights; Assert.NotNull(highlights); Assert.NotNull(highlights["content"]); Assert.Greater(highlights["content"].Highlights.Count(), 0); diff --git a/src/Nest.Tests.Integration/Integration/Query/TermToString.cs b/src/Nest.Tests.Integration/Integration/Query/TermToString.cs index a4ac6dde416..32c2773c230 100644 --- a/src/Nest.Tests.Integration/Integration/Query/TermToString.cs +++ b/src/Nest.Tests.Integration/Integration/Query/TermToString.cs @@ -20,8 +20,6 @@ public class TermToStringJson : IntegrationTests [TestFixtureSetUp] public void Initialize() { - _client.IsValid.Should().BeTrue(); - _LookFor = NestTestData.Session.Single().Get(); _LookFor.Name = "one two three four"; var status = this._client.Index(_LookFor, new IndexParameters { Refresh = true }).ConnectionStatus; diff --git a/src/Nest.Tests.Integration/Integration/Query/TextPhrasePrefixQueryTests.cs b/src/Nest.Tests.Integration/Integration/Query/TextPhrasePrefixQueryTests.cs index 0affbdb3049..d27d19c26e2 100644 --- a/src/Nest.Tests.Integration/Integration/Query/TextPhrasePrefixQueryTests.cs +++ b/src/Nest.Tests.Integration/Integration/Query/TextPhrasePrefixQueryTests.cs @@ -21,8 +21,6 @@ public class TextPhrasePrefixQueryTests : IntegrationTests [TestFixtureSetUp] public void Initialize() { - _client.IsValid.Should().BeTrue(); - _LookFor = NestTestData.Session.Single().Get(); _LookFor.Name = "one two three four"; var status = this._client.Index(_LookFor, new IndexParameters { Refresh = true }).ConnectionStatus; diff --git a/src/Nest.Tests.Integration/Integration/Query/TextPhraseQueryTests.cs b/src/Nest.Tests.Integration/Integration/Query/TextPhraseQueryTests.cs index 6eeb3c04afe..9fbebce8da4 100644 --- a/src/Nest.Tests.Integration/Integration/Query/TextPhraseQueryTests.cs +++ b/src/Nest.Tests.Integration/Integration/Query/TextPhraseQueryTests.cs @@ -22,8 +22,6 @@ public class TextPhraseQueryTests : IntegrationTests [TestFixtureSetUp] public void Initialize() { - _client.IsValid.Should().BeTrue(); - _LookFor = NestTestData.Session.Single().Get(); _LookFor.Name = "one two three four"; var status = this._client.Index(_LookFor, new IndexParameters { Refresh = true }).ConnectionStatus; diff --git a/src/Nest.Tests.Integration/IntegrationTests.cs b/src/Nest.Tests.Integration/IntegrationTests.cs index 60ebbdda193..887769386a0 100644 --- a/src/Nest.Tests.Integration/IntegrationTests.cs +++ b/src/Nest.Tests.Integration/IntegrationTests.cs @@ -36,7 +36,7 @@ protected IQueryResponse SearchRaw(string query) where T : class var index = this._client.GetIndexNameFor(); var typeName = this._client.GetTypeNameFor(); var connectionStatus = this._client.Raw.SearchPost(index, typeName, query); - return this._client.ToParsedResponse>(connectionStatus); + return connectionStatus.ToParsedResponse>(); } public void DoFilterTest(Func, Nest.BaseFilter> filter, ElasticSearchProject project, bool queryMustHaveResults) diff --git a/src/Nest.Tests.Integration/Search/QueryResponseMapperTests.cs b/src/Nest.Tests.Integration/Search/QueryResponseMapperTests.cs index 3f9a6e75c34..e907ba09b93 100644 --- a/src/Nest.Tests.Integration/Search/QueryResponseMapperTests.cs +++ b/src/Nest.Tests.Integration/Search/QueryResponseMapperTests.cs @@ -530,7 +530,7 @@ public void QueryWithHighlightTest() var queryResults = this.SearchRaw(query); //assert - Assert.IsTrue(queryResults.DocumentsWithMetaData.First().Highlight["content"].Highlights.Count() > 0); + Assert.IsTrue(queryResults.DocumentsWithMetaData.First().Highlights["content"].Highlights.Count() > 0); } } diff --git a/src/Nest.Tests.Integration/Warmers/WarmersTests.cs b/src/Nest.Tests.Integration/Warmers/WarmersTests.cs index bbd2a73ec8a..b8ef8fa8d2d 100644 --- a/src/Nest.Tests.Integration/Warmers/WarmersTests.cs +++ b/src/Nest.Tests.Integration/Warmers/WarmersTests.cs @@ -37,8 +37,8 @@ public void SimplePutAndGet() warmerResponse.Indices[_settings.DefaultIndex].Should().ContainKey("warmer_simpleputandget"); var warmerMapping = warmerResponse.Indices[_settings.DefaultIndex]["warmer_simpleputandget"]; warmerMapping.Name.Should().Be("warmer_simpleputandget"); - var typeName = typeNameResolver.GetTypeNameFor().Resolve(_client.Settings); - warmerMapping.Types.Select(s => s.Resolve(_client.Settings)).Contains(typeName).Should().Be(true); + var typeName = typeNameResolver.GetTypeNameFor().Resolve(_settings); + warmerMapping.Types.Select(s => s.Resolve(_settings)).Contains(typeName).Should().Be(true); warmerMapping.Source.Should().Contain("\"strange-value\""); } diff --git a/src/Nest.Tests.Unit/BaseJsonTests.cs b/src/Nest.Tests.Unit/BaseJsonTests.cs index 84afbcab2f0..e4de68583a9 100644 --- a/src/Nest.Tests.Unit/BaseJsonTests.cs +++ b/src/Nest.Tests.Unit/BaseJsonTests.cs @@ -41,16 +41,10 @@ protected void deb(string s) //Lazy programmers for the win! throw new Exception(s); } - protected void JsonEqualsCamelCase(object o, MethodBase method, string fileName = null) - { - //Todo find a way to have a single code path for serializations - //Serialize vs SerializeCamelCase smells a bit. - var json = _client.SerializeCamelCase(o); - this.JsonEquals(json, method, fileName); - } + protected void JsonEquals(object o, MethodBase method, string fileName = null) { - var json = _client.Serialize(o); + var json = _client.Serializer.Serialize(o); this.JsonEquals(json, method, fileName); } protected void JsonEquals(string json, MethodBase method, string fileName = null) diff --git a/src/Nest.Tests.Unit/Core/Index/IndexTests.cs b/src/Nest.Tests.Unit/Core/Index/IndexTests.cs index 38c47026db9..94d6779d7eb 100644 --- a/src/Nest.Tests.Unit/Core/Index/IndexTests.cs +++ b/src/Nest.Tests.Unit/Core/Index/IndexTests.cs @@ -13,39 +13,40 @@ namespace Nest.Tests.Unit.Core.Index { - [TestFixture] - public class IndexTests : BaseJsonTests - { - [Test] - public void IndexParameters() - { - var o = new ElasticSearchProject { Id = 1, Name = "Test" }; - var result = this._client.Index(o, new IndexParameters - { - Version = "1", + [TestFixture] + public class IndexTests : BaseJsonTests + { + [Test] + public void IndexParameters() + { + var o = new ElasticSearchProject { Id = 1, Name = "Test" }; + var result = this._client.Index(o, new IndexParameters + { + Version = "1", + }); + var status = result.ConnectionStatus; + StringAssert.Contains("version=1", status.RequestUrl); + } - }); - var status = result.ConnectionStatus; - StringAssert.Contains("version=1", status.RequestUrl); - } - - [Test] - public void GetSupportsVersioning() - { - //TODO: investigate version on get - //The elasticsearch docs make no mention of being able to specify version - //http://www.elasticsearch.org/guide/reference/api/get.html + [Test] + public void IndexingDictionaryRespectsCasing() + { + var x = new + { + FirstDictionary = new Dictionary + { + {"ALLCAPS", 1 }, + {"PascalCase", "should work as well"}, + {"camelCase", DateTime.Now} + } + }; + var result = this._client.Index(x); - //this._client.Get(g=>g.); - } - [Test] - public void UpdateSupportsVersioning() - { - //TODO: investigate version on update - //The elasticsearch docs make no mention of being able to specify version - //http://www.elasticsearch.org/guide/reference/api/get.html - - //this._client.Get(g=>g.); - } - } + var request = result.ConnectionStatus.Request; + StringAssert.Contains("ALLCAPS", request); + StringAssert.Contains("PascalCase", request); + StringAssert.Contains("camelCase", request); + StringAssert.Contains("firstDictionary", request); + } + } } diff --git a/src/Nest.Tests.Unit/Core/Update/UpdateTests.cs b/src/Nest.Tests.Unit/Core/Update/UpdateTests.cs index 515aec905c3..6f7f8b8f5c4 100644 --- a/src/Nest.Tests.Unit/Core/Update/UpdateTests.cs +++ b/src/Nest.Tests.Unit/Core/Update/UpdateTests.cs @@ -25,7 +25,7 @@ public void UpsertUsingScript() .Add("count", 1) ); - this.JsonEqualsCamelCase(s, MethodInfo.GetCurrentMethod()); + this.JsonEquals(s, MethodInfo.GetCurrentMethod()); } [Test] public void UpsertUsingScriptAndPartialObject() @@ -37,7 +37,7 @@ public void UpsertUsingScriptAndPartialObject() ) .Upsert(new { count = 4}); - this.JsonEqualsCamelCase(s, MethodInfo.GetCurrentMethod()); + this.JsonEquals(s, MethodInfo.GetCurrentMethod()); } [Test] @@ -50,7 +50,7 @@ public void UpdateUsingPartial() .Object(originalProject) //only used to infer the id .Document(partialUpdate); //the actual partial update statement; - this.JsonEqualsCamelCase(s, MethodInfo.GetCurrentMethod()); + this.JsonEquals(s, MethodInfo.GetCurrentMethod()); } } diff --git a/src/Nest.Tests.Unit/Internals/Inferno/PropertyNameResolverTests.cs b/src/Nest.Tests.Unit/Internals/Inferno/PropertyNameResolverTests.cs index f77a36e587b..7baaba04376 100644 --- a/src/Nest.Tests.Unit/Internals/Inferno/PropertyNameResolverTests.cs +++ b/src/Nest.Tests.Unit/Internals/Inferno/PropertyNameResolverTests.cs @@ -3,6 +3,7 @@ using NUnit.Framework; using System.Linq.Expressions; using Nest.Resolvers; +using Newtonsoft.Json; namespace Nest.Tests.Unit.Internals.Inferno { @@ -13,6 +14,7 @@ public class PropertyNameResolverTests : BaseJsonTests internal class SomeClass { public MyCustomClass MyCustomClass { get; set; } + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] public Dictionary StringDict { get; set; } public Dictionary IntDict { get; set; } public IList ListOfCustomClasses { get; set; } diff --git a/src/Nest.Tests.Unit/Internals/Serialize/SerializeTests.cs b/src/Nest.Tests.Unit/Internals/Serialize/SerializeTests.cs index 25a64c425ad..ba18dda3506 100644 --- a/src/Nest.Tests.Unit/Internals/Serialize/SerializeTests.cs +++ b/src/Nest.Tests.Unit/Internals/Serialize/SerializeTests.cs @@ -42,7 +42,7 @@ public void ClassWithCollectionSerializes() new SimpleClass {Id = 1, Name = "class 1"}, } }; - var json = this._client.SerializeCamelCase(col); + var json = this._client.Serializer.Serialize(col); this.JsonEquals(json, MethodInfo.GetCurrentMethod()); } } diff --git a/src/Nest.Tests.Unit/Search/Facets/ResponseDeserialisation/when_date_histogram_query_has_no_value_field.cs b/src/Nest.Tests.Unit/Search/Facets/ResponseDeserialisation/when_date_histogram_query_has_no_value_field.cs index 44957600ff1..da4ddec1198 100644 --- a/src/Nest.Tests.Unit/Search/Facets/ResponseDeserialisation/when_date_histogram_query_has_no_value_field.cs +++ b/src/Nest.Tests.Unit/Search/Facets/ResponseDeserialisation/when_date_histogram_query_has_no_value_field.cs @@ -41,13 +41,13 @@ public void should_de_serialise_date_entry_histogram() const string mockJsonResponse = @"{""took"":378,""timed_out"":false,""_shards"":{""total"":4,""successful"":4,""failed"":0},""hits"":{""total"":3700979,""max_score"":1,""hits"":[]},""facets"":{""widget_1:histogram"":{""_type"":""date_histogram"",""entries"":[{""time"":1351728000000,""count"":5181},{""time"":1354320000000,""count"":5509}]},""widget_2:histogram"":{""_type"":""date_histogram"",""entries"":[{""time"":1330560000000,""count"":173},{""time"":1333238400000,""count"":162}]},""widget_1:terms"":{""_type"":""terms"",""missing"":0,""total"":14797,""other"":0,""terms"":[{""term"":""widget 1"",""count"":14797}]},""widget_2:terms"":{""_type"":""terms"",""missing"":0,""total"":2002,""other"":0,""terms"":[{""term"":""widget 2"",""count"":2002}]}}}"; + var connectionSettings = new ConnectionSettings(Test.Default.Uri).SetDefaultIndex("index"); var connectionMockery = new Mock(); connectionMockery .Setup(status => status.PostSync("index/_search", "{}")) - .Returns(new ConnectionStatus(mockJsonResponse)); + .Returns(new ConnectionStatus(connectionSettings, mockJsonResponse)); - var connectionSettings = new ConnectionSettings(Test.Default.Uri).SetDefaultIndex("index"); var client = new ElasticClient(connectionSettings, connectionMockery.Object); var response = client.Search(descriptor => descriptor); diff --git a/src/Nest.Tests.Unit/Search/Facets/ResponseDeserialisation/when_date_histogram_query_has_value_field.cs b/src/Nest.Tests.Unit/Search/Facets/ResponseDeserialisation/when_date_histogram_query_has_value_field.cs index 1471638438c..c2f285d15b8 100644 --- a/src/Nest.Tests.Unit/Search/Facets/ResponseDeserialisation/when_date_histogram_query_has_value_field.cs +++ b/src/Nest.Tests.Unit/Search/Facets/ResponseDeserialisation/when_date_histogram_query_has_value_field.cs @@ -62,12 +62,12 @@ public void should_de_serialise_date_entry_histogram() @"{""took"":378,""timed_out"":false,""_shards"":{""total"":4,""successful"":4,""failed"":0},""hits"":{""total"":3700979,""max_score"":1,""hits"":[]},""facets"":{""widget_1:histogram"":{""_type"":""date_histogram"",""entries"":[{""time"":1351728000000,""count"":5181,""min"":7.989999771118164,""max"":7.989999771118164,""total"":41396.18881416321,""total_count"":5181,""mean"":7.989999771118164},{""time"":1354320000000,""count"":5509,""min"":7.989999771118164,""max"":7.989999771118164,""total"":44016.908739089966,""total_count"":5509,""mean"":7.989999771118164}]},""widget_2:histogram"":{""_type"":""date_histogram"",""entries"":[{""time"":1330560000000,""count"":173,""min"":7.989999771118164,""max"":7.989999771118164,""total"":1382.2699604034424,""total_count"":173,""mean"":7.989999771118164},{""time"":1333238400000,""count"":162,""min"":7.989999771118164,""max"":7.989999771118164,""total"":1294.3799629211426,""total_count"":162,""mean"":7.989999771118164}]},""widget_1:terms"":{""_type"":""terms"",""missing"":0,""total"":14797,""other"":0,""terms"":[{""term"":""widget 1"",""count"":14797}]},""widget_2:terms"":{""_type"":""terms"",""missing"":0,""total"":2002,""other"":0,""terms"":[{""term"":""widget 2"",""count"":2002}]}}}"; var connectionMockery = new Mock(); + var connectionSettings = new ConnectionSettings(Test.Default.Uri).SetDefaultIndex("index"); connectionMockery .Setup(status => status.PostSync("index/_search", "{}")) - .Returns(new ConnectionStatus(mockJsonResponse)); + .Returns(new ConnectionStatus(connectionSettings, mockJsonResponse)); - var connectionSettings = new ConnectionSettings(Test.Default.Uri).SetDefaultIndex("index"); var client = new ElasticClient(connectionSettings, connectionMockery.Object); var response = client.Search(descriptor => descriptor); diff --git a/src/Nest.Tests.Unit/TestElasticClient.cs b/src/Nest.Tests.Unit/TestElasticClient.cs index f58d746314b..8c486c4a45a 100644 --- a/src/Nest.Tests.Unit/TestElasticClient.cs +++ b/src/Nest.Tests.Unit/TestElasticClient.cs @@ -16,11 +16,7 @@ static TestElasticClient() } public static string Serialize(T obj) { - return Client.Serialize(obj); - } - public static string SerializeCamelCase(T obj) - { - return Client.SerializeCamelCase(obj); + return Client.Serializer.Serialize(obj); } } } diff --git a/src/Nest.sln b/src/Nest.sln index 5c705fa10c6..2b92d88da34 100644 --- a/src/Nest.sln +++ b/src/Nest.sln @@ -4,8 +4,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Nest", "Nest\Nest.csproj", EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Nest.Tests.Integration", "Nest.Tests.Integration\Nest.Tests.Integration.csproj", "{9E38CD2C-EEFD-4C82-B0CD-D0608C27D64F}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HackerNews.Indexer", "HackerNews.Indexer\HackerNews.Indexer.csproj", "{E39CC264-A7B3-490D-84B2-D3016D86CD87}" -EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "_Notes", "_Notes", "{E30CA256-C9A8-487A-94B7-D6B79D70F774}" ProjectSection(SolutionItems) = preProject license.txt = license.txt @@ -70,18 +68,6 @@ Global {9E38CD2C-EEFD-4C82-B0CD-D0608C27D64F}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {9E38CD2C-EEFD-4C82-B0CD-D0608C27D64F}.Release|Mixed Platforms.Build.0 = Release|Any CPU {9E38CD2C-EEFD-4C82-B0CD-D0608C27D64F}.Release|x86.ActiveCfg = Release|Any CPU - {E39CC264-A7B3-490D-84B2-D3016D86CD87}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {E39CC264-A7B3-490D-84B2-D3016D86CD87}.Debug|Any CPU.Build.0 = Debug|Any CPU - {E39CC264-A7B3-490D-84B2-D3016D86CD87}.Debug|Mixed Platforms.ActiveCfg = Debug|x86 - {E39CC264-A7B3-490D-84B2-D3016D86CD87}.Debug|Mixed Platforms.Build.0 = Debug|x86 - {E39CC264-A7B3-490D-84B2-D3016D86CD87}.Debug|x86.ActiveCfg = Debug|x86 - {E39CC264-A7B3-490D-84B2-D3016D86CD87}.Debug|x86.Build.0 = Debug|x86 - {E39CC264-A7B3-490D-84B2-D3016D86CD87}.Release|Any CPU.ActiveCfg = Release|Any CPU - {E39CC264-A7B3-490D-84B2-D3016D86CD87}.Release|Any CPU.Build.0 = Release|Any CPU - {E39CC264-A7B3-490D-84B2-D3016D86CD87}.Release|Mixed Platforms.ActiveCfg = Release|x86 - {E39CC264-A7B3-490D-84B2-D3016D86CD87}.Release|Mixed Platforms.Build.0 = Release|x86 - {E39CC264-A7B3-490D-84B2-D3016D86CD87}.Release|x86.ActiveCfg = Release|x86 - {E39CC264-A7B3-490D-84B2-D3016D86CD87}.Release|x86.Build.0 = Release|x86 {27143A05-5655-447C-ADAF-405E1CF43741}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {27143A05-5655-447C-ADAF-405E1CF43741}.Debug|Any CPU.Build.0 = Debug|Any CPU {27143A05-5655-447C-ADAF-405E1CF43741}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU @@ -147,7 +133,6 @@ Global HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution - {E39CC264-A7B3-490D-84B2-D3016D86CD87} = {DDC38E1C-13BF-4C96-A3BF-60F14DFC5069} {B9FE4875-0171-40F7-A357-064A93BE09C6} = {DDC38E1C-13BF-4C96-A3BF-60F14DFC5069} {2727A374-9866-4A9D-9A40-6175334B5992} = {DDC38E1C-13BF-4C96-A3BF-60F14DFC5069} EndGlobalSection diff --git a/src/Nest/DSL/BulkUpdateDescriptor.cs b/src/Nest/DSL/BulkUpdateDescriptor.cs index 94f14137ee6..09b4e792a62 100644 --- a/src/Nest/DSL/BulkUpdateDescriptor.cs +++ b/src/Nest/DSL/BulkUpdateDescriptor.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Globalization; using Nest.Resolvers; +using Nest.Resolvers.Converters; using Newtonsoft.Json; namespace Nest @@ -14,8 +15,11 @@ internal class BulkUpdateBody internal K _Document { get; set; } [JsonProperty(PropertyName = "script")] internal string _Script { get; set; } + [JsonProperty(PropertyName = "params")] + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] internal Dictionary _Params { get; set; } + [JsonProperty(PropertyName = "upsert")] internal object _Upsert { get; set; } } diff --git a/src/Nest/DSL/Facets/DateHistogramFacetDescriptor.cs b/src/Nest/DSL/Facets/DateHistogramFacetDescriptor.cs index 8b367f731ba..fb92c62b4eb 100644 --- a/src/Nest/DSL/Facets/DateHistogramFacetDescriptor.cs +++ b/src/Nest/DSL/Facets/DateHistogramFacetDescriptor.cs @@ -47,7 +47,8 @@ public class DateHistogramFacetDescriptor : BaseFacetDescriptor where T : internal string _PostOffset { get; set; } [JsonProperty(PropertyName = "params")] - internal Dictionary _Params { get; set; } + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] + internal Dictionary _Params { get; set; } public DateHistogramFacetDescriptor OnField(string field) { diff --git a/src/Nest/DSL/Facets/GeoDistanceFacetDescriptor.cs b/src/Nest/DSL/Facets/GeoDistanceFacetDescriptor.cs index 20da7dd7621..5eec6601ee0 100644 --- a/src/Nest/DSL/Facets/GeoDistanceFacetDescriptor.cs +++ b/src/Nest/DSL/Facets/GeoDistanceFacetDescriptor.cs @@ -28,6 +28,7 @@ public class GeoDistanceFacetDescriptor internal GeoDistance? _GeoDistance { get; set; } + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] internal Dictionary _Params { get; set; } } diff --git a/src/Nest/DSL/Facets/HistogramFacetDescriptor.cs b/src/Nest/DSL/Facets/HistogramFacetDescriptor.cs index f97bc71c6ef..20ddc50aba4 100644 --- a/src/Nest/DSL/Facets/HistogramFacetDescriptor.cs +++ b/src/Nest/DSL/Facets/HistogramFacetDescriptor.cs @@ -34,7 +34,8 @@ public class HistogramFacetDescriptor : BaseFacetDescriptor where T : clas internal string _TimeInterval { get; set; } [JsonProperty(PropertyName = "params")] - internal Dictionary _Params { get; set; } + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] + internal Dictionary _Params { get; set; } public HistogramFacetDescriptor OnField(string field) { diff --git a/src/Nest/DSL/Facets/StatisticalFacetDescriptor.cs b/src/Nest/DSL/Facets/StatisticalFacetDescriptor.cs index 95e70a0ab1c..817e303d24e 100644 --- a/src/Nest/DSL/Facets/StatisticalFacetDescriptor.cs +++ b/src/Nest/DSL/Facets/StatisticalFacetDescriptor.cs @@ -22,7 +22,8 @@ public class StatisticalFacetDescriptor : BaseFacetDescriptor where T : cl internal string _Script { get; set; } [JsonProperty(PropertyName = "params")] - internal Dictionary _Params { get; set; } + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] + internal Dictionary _Params { get; set; } public StatisticalFacetDescriptor OnField(string field) { diff --git a/src/Nest/DSL/Facets/TermsStatsFacetDescriptor.cs b/src/Nest/DSL/Facets/TermsStatsFacetDescriptor.cs index b25df6ed0ad..0d292f3fa66 100644 --- a/src/Nest/DSL/Facets/TermsStatsFacetDescriptor.cs +++ b/src/Nest/DSL/Facets/TermsStatsFacetDescriptor.cs @@ -38,7 +38,8 @@ public class TermsStatsFacetDescriptor : BaseFacetDescriptor where T : cla internal int? _Size { get; set; } [JsonProperty(PropertyName = "params")] - internal Dictionary _Params { get; set; } + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] + internal Dictionary _Params { get; set; } public TermsStatsFacetDescriptor KeyField(Expression> objectPath) { diff --git a/src/Nest/DSL/Filter/ScriptFilterDescriptor.cs b/src/Nest/DSL/Filter/ScriptFilterDescriptor.cs index 300a3cdd75c..cf5809332aa 100644 --- a/src/Nest/DSL/Filter/ScriptFilterDescriptor.cs +++ b/src/Nest/DSL/Filter/ScriptFilterDescriptor.cs @@ -17,6 +17,7 @@ public class ScriptFilterDescriptor : FilterBase internal string _Script { get; set; } [JsonProperty(PropertyName = "params")] + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] internal Dictionary _Params { get; set; } [JsonProperty(PropertyName = "lang")] diff --git a/src/Nest/DSL/FilterDescriptor.cs b/src/Nest/DSL/FilterDescriptor.cs index 769dbe65c5c..a6fda84ef2e 100644 --- a/src/Nest/DSL/FilterDescriptor.cs +++ b/src/Nest/DSL/FilterDescriptor.cs @@ -52,15 +52,19 @@ public FilterDescriptor Cache(bool cache) internal IdsFilter IdsFilter { get; set; } [JsonProperty(PropertyName = "geo_bounding_box")] + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] internal Dictionary GeoBoundingBoxFilter { get; set; } [JsonProperty(PropertyName = "geo_distance")] + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] internal Dictionary GeoDistanceFilter { get; set; } [JsonProperty(PropertyName = "geo_distance_range")] + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] internal Dictionary GeoDistanceRangeFilter { get; set; } [JsonProperty(PropertyName = "geo_polygon")] + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] internal Dictionary GeoPolygonFilter { get; set; } [JsonProperty(PropertyName = "limit")] @@ -79,30 +83,39 @@ public FilterDescriptor Cache(bool cache) internal object HasParentFilter { get; set; } [JsonProperty(PropertyName = "numeric_range")] + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] internal Dictionary NumericRangeFilter { get; set; } [JsonProperty(PropertyName = "range")] + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] internal Dictionary RangeFilter { get; set; } [JsonProperty(PropertyName = "prefix")] + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] internal Dictionary PrefixFilter { get; set; } [JsonProperty(PropertyName = "term")] + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] internal Dictionary TermFilter { get; set; } [JsonProperty(PropertyName = "terms")] + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] internal Dictionary TermsFilter { get; set; } [JsonProperty(PropertyName = "fquery")] + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] internal Dictionary QueryFilter { get; set; } [JsonProperty(PropertyName = "and")] + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] internal Dictionary AndFilter { get; set; } [JsonProperty(PropertyName = "or")] + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] internal Dictionary OrFilter { get; set; } [JsonProperty(PropertyName = "not")] + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] internal Dictionary NotFilter { get; set; } [JsonProperty(PropertyName = "bool")] diff --git a/src/Nest/DSL/HighlightDescriptor.cs b/src/Nest/DSL/HighlightDescriptor.cs index 093df05411a..0d102ee273d 100644 --- a/src/Nest/DSL/HighlightDescriptor.cs +++ b/src/Nest/DSL/HighlightDescriptor.cs @@ -33,7 +33,8 @@ public class HighlightDescriptor where T : class internal string _Order { get; set; } [JsonProperty(PropertyName = "fields")] - internal Dictionary> _Fields { get; set; } + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] + internal Dictionary> _Fields { get; set; } [JsonProperty("require_field_match")] internal bool? _RequireFieldMatch { get; set; } diff --git a/src/Nest/DSL/MultiSearchDescriptor.cs b/src/Nest/DSL/MultiSearchDescriptor.cs index 0fb3cca62ee..6abb32ec74b 100644 --- a/src/Nest/DSL/MultiSearchDescriptor.cs +++ b/src/Nest/DSL/MultiSearchDescriptor.cs @@ -4,6 +4,8 @@ using System.Text; using System.Linq.Expressions; using Nest.Domain; +using Nest.Resolvers.Converters; +using Newtonsoft.Json; namespace Nest { @@ -12,6 +14,7 @@ public class MultiSearchDescriptor internal string _FixedIndex { get; set; } internal string _FixedType { get; set; } + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] internal IDictionary _Operations = new Dictionary(); public MultiSearchDescriptor Search(string name, Func, SearchDescriptor> searchSelector) where T : class diff --git a/src/Nest/DSL/Query/CustomFiltersScoreDescriptor.cs b/src/Nest/DSL/Query/CustomFiltersScoreDescriptor.cs index b1925f32a19..791ba851f0d 100644 --- a/src/Nest/DSL/Query/CustomFiltersScoreDescriptor.cs +++ b/src/Nest/DSL/Query/CustomFiltersScoreDescriptor.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using System.Text; +using Nest.Resolvers.Converters; using Newtonsoft.Json; using Nest.DSL.Query; using Newtonsoft.Json.Converters; @@ -21,8 +22,9 @@ public class CustomFiltersScoreDescriptor : IQuery where T : class [JsonConverter(typeof(StringEnumConverter))] internal ScoreMode _ScoreMode { get; set; } - [JsonProperty(PropertyName = "params")] - internal Dictionary _Params { get; set; } + [JsonProperty(PropertyName = "params")] + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] + internal Dictionary _Params { get; set; } [JsonProperty(PropertyName = "lang")] internal string _Lang { get; set; } diff --git a/src/Nest/DSL/Query/CustomScoreQueryDescriptor.cs b/src/Nest/DSL/Query/CustomScoreQueryDescriptor.cs index eca42d668d4..235f465d1de 100644 --- a/src/Nest/DSL/Query/CustomScoreQueryDescriptor.cs +++ b/src/Nest/DSL/Query/CustomScoreQueryDescriptor.cs @@ -2,8 +2,9 @@ using System.Collections.Generic; using System.Linq; using System.Text; -using Newtonsoft.Json; - +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; + namespace Nest { [JsonObject(MemberSerialization = MemberSerialization.OptIn)] @@ -15,7 +16,8 @@ public class CustomScoreQueryDescriptor : IQuery where T : class [JsonProperty(PropertyName = "script")] internal string _Script { get; set; } - [JsonProperty(PropertyName = "params")] + [JsonProperty(PropertyName = "params")] + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] internal Dictionary _Params { get; set; } [JsonProperty(PropertyName = "query")] diff --git a/src/Nest/DSL/QueryDescriptor.cs b/src/Nest/DSL/QueryDescriptor.cs index 06c2a2d3864..4165e46542c 100644 --- a/src/Nest/DSL/QueryDescriptor.cs +++ b/src/Nest/DSL/QueryDescriptor.cs @@ -47,15 +47,20 @@ public QueryDescriptor() internal DismaxQueryDescriptor DismaxQueryDescriptor { get; set; } [JsonProperty(PropertyName = "filtered")] internal FilteredQueryDescriptor FilteredQueryDescriptor { get; set; } + [JsonProperty(PropertyName = "text")] + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] internal IDictionary TextQueryDescriptor { get; set; } [JsonProperty(PropertyName = "multi_match")] internal MultiMatchQueryDescriptor MultiMatchQueryDescriptor { get; set; } [JsonProperty(PropertyName = "match")] + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] internal IDictionary MatchQueryDescriptor { get; set; } + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] [JsonProperty(PropertyName = "fuzzy")] internal IDictionary FuzzyQueryDescriptor { get; set; } [JsonProperty(PropertyName = "terms")] + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] internal IDictionary TermsQueryDescriptor { get; set; } [JsonProperty(PropertyName = "query_string")] internal QueryStringDescriptor QueryStringDescriptor { get; set; } @@ -69,6 +74,7 @@ public QueryDescriptor() [JsonProperty(PropertyName = "mlt")] internal MoreLikeThisQueryDescriptor MoreLikeThisDescriptor { get; set; } [JsonProperty(PropertyName = "range")] + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] internal IDictionary RangeQueryDescriptor { get; set; } [JsonProperty(PropertyName = "span_term")] diff --git a/src/Nest/DSL/SearchDescriptor.cs b/src/Nest/DSL/SearchDescriptor.cs index 83dce512800..da48c560fb2 100644 --- a/src/Nest/DSL/SearchDescriptor.cs +++ b/src/Nest/DSL/SearchDescriptor.cs @@ -192,12 +192,15 @@ public SearchDescriptor Strict(bool strict = true) internal double? _MinScore { get; set; } [JsonProperty(PropertyName = "indices_boost")] + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] internal IDictionary _IndicesBoost { get; set; } [JsonProperty(PropertyName = "sort")] + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] internal IDictionary _Sort { get; set; } [JsonProperty(PropertyName = "facets")] + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] internal IDictionary> _Facets { get; set; } [JsonProperty(PropertyName = "query")] @@ -246,10 +249,12 @@ internal RawOrFilterDescriptor _FilterOrRaw internal IList _Fields { get; set; } [JsonProperty(PropertyName = "script_fields")] - internal FluentDictionary _ScriptFields { get; set; } + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] + internal FluentDictionary _ScriptFields { get; set; } [JsonProperty(PropertyName = "partial_fields")] - internal Dictionary> _PartialFields { get; set; } + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] + internal Dictionary> _PartialFields { get; set; } /// /// The number of hits to return. Defaults to 10. When using scroll search type diff --git a/src/Nest/DSL/SortScriptDescriptor.cs b/src/Nest/DSL/SortScriptDescriptor.cs index 4522b67917b..74adf0f46c5 100644 --- a/src/Nest/DSL/SortScriptDescriptor.cs +++ b/src/Nest/DSL/SortScriptDescriptor.cs @@ -22,7 +22,8 @@ public class SortScriptDescriptor internal string _Script { get; set; } [JsonProperty(PropertyName = "params")] - internal Dictionary _Params { get; set; } + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] + internal Dictionary _Params { get; set; } public SortScriptDescriptor Script(string script) { diff --git a/src/Nest/DSL/TemplateMappingDescriptor.cs b/src/Nest/DSL/TemplateMappingDescriptor.cs index 2f32a34b05c..7b4733cf119 100644 --- a/src/Nest/DSL/TemplateMappingDescriptor.cs +++ b/src/Nest/DSL/TemplateMappingDescriptor.cs @@ -15,11 +15,13 @@ public class TemplateMappingDescriptor internal string _Name { get; set; } internal TemplateMapping _TemplateMapping { get; set; } - private readonly JsonSerializerSettings _serializationSettings; + private readonly ElasticSerializer _serializer; + public TemplateMappingDescriptor(IConnectionSettings connectionSettings) { this._TemplateMapping = new TemplateMapping(); this._connectionSettings = connectionSettings; + this._serializer = new ElasticSerializer(this._connectionSettings); } public TemplateMappingDescriptor Name(string name) @@ -85,7 +87,6 @@ public TemplateMappingDescriptor RemoveMapping(string typeName) return this; } - public TemplateMappingDescriptor AddWarmer(Func warmerSelector) where T : class { @@ -94,7 +95,7 @@ public TemplateMappingDescriptor AddWarmer(Func _Params { get; set; } [JsonProperty(PropertyName = "upsert")] diff --git a/src/Nest/Domain/Analysis/Analyzers/AnalysisSettings.cs b/src/Nest/Domain/Analysis/Analyzers/AnalysisSettings.cs index bc482b40bf2..17e7ef3b98d 100644 --- a/src/Nest/Domain/Analysis/Analyzers/AnalysisSettings.cs +++ b/src/Nest/Domain/Analysis/Analyzers/AnalysisSettings.cs @@ -1,4 +1,6 @@ using System.Collections.Generic; +using Nest.Resolvers.Converters; +using Newtonsoft.Json; namespace Nest { @@ -12,9 +14,16 @@ public AnalysisSettings() this.CharFilters = new Dictionary(); } + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] public IDictionary Analyzers { get; set; } - public IDictionary TokenFilters { get; set; } + + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] + public IDictionary TokenFilters { get; set; } + + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] public IDictionary Tokenizers { get; set; } + + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] public IDictionary CharFilters { get; set; } } } \ No newline at end of file diff --git a/src/Nest/Domain/Connection/AsyncRequestOperation.cs b/src/Nest/Domain/Connection/AsyncRequestOperation.cs index 5363340829b..b36ac9f9e4e 100644 --- a/src/Nest/Domain/Connection/AsyncRequestOperation.cs +++ b/src/Nest/Domain/Connection/AsyncRequestOperation.cs @@ -90,7 +90,7 @@ private void Done(Stream result) { result.Position = 0; var reader = new StreamReader(result); - Done(new ConnectionStatus(reader.ReadToEnd()) + Done(new ConnectionStatus(this.m_connectionSettings, reader.ReadToEnd()) { Request = this.m_requestData, RequestUrl = this.m_request.RequestUri.ToString(), @@ -109,7 +109,7 @@ private AsyncCallback Monitor(AsyncCallback callback) } catch (WebException webException) { - var connectionStatus = new ConnectionStatus(webException) + var connectionStatus = new ConnectionStatus(this.m_connectionSettings, webException) { Request = this.m_requestData, RequestUrl = this.m_request.RequestUri.ToString(), diff --git a/src/Nest/Domain/Connection/Connection.cs b/src/Nest/Domain/Connection/Connection.cs index 96149ca1bfa..d86876f96d9 100644 --- a/src/Nest/Domain/Connection/Connection.cs +++ b/src/Nest/Domain/Connection/Connection.cs @@ -182,7 +182,7 @@ protected virtual ConnectionStatus DoSynchronousRequest(HttpWebRequest request, using (var streamReader = new StreamReader(responseStream)) { string result = streamReader.ReadToEnd(); - cs = new ConnectionStatus(result) + cs = new ConnectionStatus(this._ConnectionSettings, result) { Request = data, RequestUrl = request.RequestUri.ToString(), @@ -194,7 +194,7 @@ protected virtual ConnectionStatus DoSynchronousRequest(HttpWebRequest request, } catch (WebException webException) { - cs = new ConnectionStatus(webException) + cs = new ConnectionStatus(this._ConnectionSettings, webException) { Request = data, RequestUrl = request.RequestUri.ToString(), @@ -223,7 +223,7 @@ protected virtual Task DoAsyncRequest(HttpWebRequest request, { var m = "Could not start the operation before the timeout of " + timeout + "ms completed while waiting for the semaphore"; - var cs = new ConnectionStatus(new TimeoutException(m)); + var cs = new ConnectionStatus(this._ConnectionSettings, new TimeoutException(m)); tcs.SetResult(cs); tracer.SetResult(cs); return tcs.Task; @@ -294,7 +294,7 @@ private IEnumerable _AsyncSteps(HttpWebRequest request, TaskCompletionSour // Decode the data and store the result var result = Encoding.UTF8.GetString(output.ToArray()); - var cs = new ConnectionStatus(result) { Request = data, RequestUrl = request.RequestUri.ToString(), RequestMethod = request.Method }; + var cs = new ConnectionStatus(this._ConnectionSettings, result) { Request = data, RequestUrl = request.RequestUri.ToString(), RequestMethod = request.Method }; tcs.TrySetResult(cs); tracer.SetResult(cs); _ConnectionSettings.ConnectionStatusHandler(cs); @@ -318,7 +318,7 @@ public void Iterate(IEnumerable asyncIterator, TaskCompletionSource DefaultIndices { get; private set; } public FluentDictionary DefaultTypeNames { get; private set; } public NameValueCollection QueryStringParameters { get; private set; } + public Func DefaultPropertyNameInferrer { get; private set; } public ConnectionSettings(Uri uri) { @@ -160,6 +161,19 @@ private void ConnectionStatusDefaultHandler(ConnectionStatus status) return; } + /// + /// By default NEST camelCases property names (EmailAddress => emailAddress) that do not have an explicit propertyname + /// either via an ElasticProperty attribute or because they are part of Dictionary where the keys should be treated verbatim. + ///
+    /// Here you can register a function that transforms propertynames (default casing, pre- or suffixing)
+    /// 
+ ///
+ public ConnectionSettings SetDefaultPropertyNameInferrer(Func propertyNameSelector) + { + this.DefaultPropertyNameInferrer = propertyNameSelector; + return this; + } + public ConnectionSettings SetDefaultTypeNameInferrer(Func defaultTypeNameInferrer) { defaultTypeNameInferrer.ThrowIfNull("defaultTypeNameInferrer"); @@ -187,5 +201,6 @@ public ConnectionSettings MapDefaultTypeNames(Action + /// Returns a response of type R based on the connection status by trying parsing status.Result into R + ///
+ /// + public virtual R ToParsedResponse(bool allow404 = false, IEnumerable extraConverters = null) where R : BaseResponse + { + return this._elasticSerializer.ToParsedResponse(this, allow404, extraConverters); + } + public override string ToString() { var r = this; diff --git a/src/Nest/Domain/Connection/IConnectionSettings.cs b/src/Nest/Domain/Connection/IConnectionSettings.cs index 1a46eecc992..de31cde3e1e 100644 --- a/src/Nest/Domain/Connection/IConnectionSettings.cs +++ b/src/Nest/Domain/Connection/IConnectionSettings.cs @@ -1,28 +1,30 @@ -using System; +using System; using System.Collections.Specialized; - -namespace Nest -{ - public interface IConnectionSettings - { - FluentDictionary DefaultIndices { get; } - FluentDictionary DefaultTypeNames { get; } - string DefaultIndex { get; } - Uri Uri { get; } - int MaximumAsyncConnections { get; } - string Host { get; } - int Port { get; } - int Timeout { get; } - string ProxyAddress { get; } - string ProxyUsername { get; } - string ProxyPassword { get; } - - bool TraceEnabled { get; } - bool DontDoubleEscapePathDotsAndSlashes { get; } - NameValueCollection QueryStringParameters { get; } - Action ConnectionStatusHandler { get; } +namespace Nest +{ + public interface IConnectionSettings + { + FluentDictionary DefaultIndices { get; } + FluentDictionary DefaultTypeNames { get; } + string DefaultIndex { get; } - Func DefaultTypeNameInferrer { get; } - } -} + Uri Uri { get; } + int MaximumAsyncConnections { get; } + string Host { get; } + int Port { get; } + int Timeout { get; } + string ProxyAddress { get; } + string ProxyUsername { get; } + string ProxyPassword { get; } + + bool TraceEnabled { get; } + bool DontDoubleEscapePathDotsAndSlashes { get; } + NameValueCollection QueryStringParameters { get; } + Action ConnectionStatusHandler { get; } + + Func DefaultPropertyNameInferrer { get; } + + Func DefaultTypeNameInferrer { get; } + } +} diff --git a/src/Nest/Domain/Connection/InMemoryConnection.cs b/src/Nest/Domain/Connection/InMemoryConnection.cs index 6dc2a5db198..88d3e2cbc92 100644 --- a/src/Nest/Domain/Connection/InMemoryConnection.cs +++ b/src/Nest/Domain/Connection/InMemoryConnection.cs @@ -35,7 +35,7 @@ protected override ConnectionStatus DoSynchronousRequest(HttpWebRequest request, private ConnectionStatus ReturnConnectionStatus(HttpWebRequest request, string data) { - return this._fixedResult ?? new ConnectionStatus("{ \"status\" : \"USING NEST IN MEMORY CONNECTION\" }") + return this._fixedResult ?? new ConnectionStatus(this._ConnectionSettings, "{ \"status\" : \"USING NEST IN MEMORY CONNECTION\" }") { Request = data, RequestUrl = request.RequestUri.ToString(), diff --git a/src/Nest/Domain/FieldSelection.cs b/src/Nest/Domain/FieldSelection.cs index 27abce0fb66..1b029009b7e 100644 --- a/src/Nest/Domain/FieldSelection.cs +++ b/src/Nest/Domain/FieldSelection.cs @@ -1,4 +1,6 @@ using Nest.Resolvers; +using Nest.Resolvers.Converters; +using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections; @@ -17,6 +19,8 @@ public interface IFieldSelection public class FieldSelection : IFieldSelection { public T Document { get; set; } + + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] internal IDictionary FieldValues { get; set; } public K FieldValue(Expression> objectPath) diff --git a/src/Nest/Domain/Hit/HighlightCollection.cs b/src/Nest/Domain/Hit/HighlightCollection.cs index 79a244fbac5..6b151def1f5 100644 --- a/src/Nest/Domain/Hit/HighlightCollection.cs +++ b/src/Nest/Domain/Hit/HighlightCollection.cs @@ -2,9 +2,13 @@ using System.Collections.Generic; using System.Linq; using System.Windows.Forms; +using Nest.Resolvers.Converters; +using Newtonsoft.Json; namespace Nest { + + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] public class HighlightFieldDictionary : Dictionary { public HighlightFieldDictionary(IDictionary dictionary = null) @@ -17,6 +21,8 @@ public HighlightFieldDictionary(IDictionary dictionary = null } } } + + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] public class HighlightDocumentDictionary : Dictionary { diff --git a/src/Nest/Domain/Hit/Hit.cs b/src/Nest/Domain/Hit/Hit.cs index 674542ee3f9..c0541e82bd1 100644 --- a/src/Nest/Domain/Hit/Hit.cs +++ b/src/Nest/Domain/Hit/Hit.cs @@ -19,7 +19,7 @@ public interface IHit where T : class IEnumerable Sorts { get; } - HighlightFieldDictionary Highlight { get; } + HighlightFieldDictionary Highlights { get; } Explanation Explanation { get; } ICovariantDictionary PartialFields { get; } } @@ -47,9 +47,10 @@ public class Hit : IHit public IEnumerable Sorts { get; internal set; } [JsonProperty(PropertyName = "highlight")] + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] internal Dictionary> _Highlight { get; set; } - public HighlightFieldDictionary Highlight + public HighlightFieldDictionary Highlights { get { diff --git a/src/Nest/Domain/Hit/IndexSegment.cs b/src/Nest/Domain/Hit/IndexSegment.cs index f1f6ccae97e..1450b59ec4a 100644 --- a/src/Nest/Domain/Hit/IndexSegment.cs +++ b/src/Nest/Domain/Hit/IndexSegment.cs @@ -7,6 +7,7 @@ namespace Nest public class IndexSegment { [JsonProperty(PropertyName = "shards")] - public Dictionary Shards { get; internal set; } + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] + public Dictionary Shards { get; internal set; } } } \ No newline at end of file diff --git a/src/Nest/Domain/Hit/ShardsSegment.cs b/src/Nest/Domain/Hit/ShardsSegment.cs index ea030aac760..62845303ccc 100644 --- a/src/Nest/Domain/Hit/ShardsSegment.cs +++ b/src/Nest/Domain/Hit/ShardsSegment.cs @@ -17,8 +17,9 @@ public class ShardsSegment [JsonProperty(PropertyName = "routing")] public ShardSegmentRouting Routing { get; internal set; } - [JsonProperty] - public Dictionary Segments { get; internal set; } + [JsonProperty] + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] + public Dictionary Segments { get; internal set; } } } \ No newline at end of file diff --git a/src/Nest/Domain/Mapping/Descriptors/CorePropertiesDescriptor.cs b/src/Nest/Domain/Mapping/Descriptors/CorePropertiesDescriptor.cs index f800e6bf857..03e2ce55f8b 100644 --- a/src/Nest/Domain/Mapping/Descriptors/CorePropertiesDescriptor.cs +++ b/src/Nest/Domain/Mapping/Descriptors/CorePropertiesDescriptor.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using Nest.Resolvers.Converters; using Newtonsoft.Json; using Nest.Resolvers.Writers; @@ -7,6 +8,7 @@ namespace Nest { public class CorePropertiesDescriptor where T : class { + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] public IDictionary Properties { get; private set; } internal IList _Deletes = new List(); diff --git a/src/Nest/Domain/Mapping/Descriptors/PropertiesDescriptor.cs b/src/Nest/Domain/Mapping/Descriptors/PropertiesDescriptor.cs index ddf955b2768..5841bc07d5e 100644 --- a/src/Nest/Domain/Mapping/Descriptors/PropertiesDescriptor.cs +++ b/src/Nest/Domain/Mapping/Descriptors/PropertiesDescriptor.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using Nest.Resolvers.Converters; using Newtonsoft.Json; using Nest.Resolvers.Writers; @@ -8,6 +9,8 @@ namespace Nest public class PropertiesDescriptor where T : class { private readonly IConnectionSettings _connectionSettings; + + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] public IDictionary Properties { get; private set; } internal IList _Deletes = new List(); diff --git a/src/Nest/Domain/Mapping/Types/RootObjectMapping.cs b/src/Nest/Domain/Mapping/Types/RootObjectMapping.cs index c1bc6cd0da5..3767ce95fae 100644 --- a/src/Nest/Domain/Mapping/Types/RootObjectMapping.cs +++ b/src/Nest/Domain/Mapping/Types/RootObjectMapping.cs @@ -66,6 +66,7 @@ public class RootObjectMapping : ObjectMapping public TtlFieldMapping TtlFieldMapping { get; set; } [JsonProperty("_meta")] + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] public FluentDictionary Meta { get; set; } [JsonProperty("dynamic_templates", TypeNameHandling = TypeNameHandling.None)] diff --git a/src/Nest/Domain/Mapping/Types/TemplateMapping.cs b/src/Nest/Domain/Mapping/Types/TemplateMapping.cs index dbc174b2310..41dd3e4f9b6 100644 --- a/src/Nest/Domain/Mapping/Types/TemplateMapping.cs +++ b/src/Nest/Domain/Mapping/Types/TemplateMapping.cs @@ -23,12 +23,15 @@ public TemplateMapping() public int Order { get; set; } [JsonProperty("settings")] + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] public FluentDictionary Settings { get; set; } [JsonProperty("mappings")] + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] public Dictionary Mappings { get; set; } [JsonProperty("warmers")] + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] public Dictionary Warmers { get; set; } } } \ No newline at end of file diff --git a/src/Nest/Domain/Responses/ClusterStateResponse.cs b/src/Nest/Domain/Responses/ClusterStateResponse.cs index 11595394fd9..5b60add55b1 100644 --- a/src/Nest/Domain/Responses/ClusterStateResponse.cs +++ b/src/Nest/Domain/Responses/ClusterStateResponse.cs @@ -26,7 +26,8 @@ public ClusterStateResponse() public string MasterNode { get; internal set; } [JsonProperty("nodes")] - public Dictionary Nodes { get; internal set; } + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] + public Dictionary Nodes { get; internal set; } [JsonProperty("metadata")] public MetadataState Metadata { get; internal set; } diff --git a/src/Nest/Domain/Responses/ElasticSearchVersionInfo.cs b/src/Nest/Domain/Responses/ElasticSearchVersionInfo.cs index 1915274dc0e..92305f32cf8 100644 --- a/src/Nest/Domain/Responses/ElasticSearchVersionInfo.cs +++ b/src/Nest/Domain/Responses/ElasticSearchVersionInfo.cs @@ -3,18 +3,15 @@ namespace Nest { - public interface IElasticSearchVersionInfo - { - string Number { get; set; } - DateTime Date { get; set; } - bool IsSnapShotBuild { get; set; } - } - public class ElasticSearchVersionInfo : IElasticSearchVersionInfo + public class ElasticSearchVersionInfo { public string Number { get; set; } - public DateTime Date { get; set; } + [JsonProperty(PropertyName = "snapshot_build")] - public bool IsSnapShotBuild { get; set; } + public bool IsSnapShotBuild { get; set; } + + [JsonProperty(PropertyName = "lucene_version")] + public string LuceneVersion { get; set; } } } diff --git a/src/Nest/Domain/Responses/GlobalStatsResponse.cs b/src/Nest/Domain/Responses/GlobalStatsResponse.cs index d98873e4c68..7f22181093f 100644 --- a/src/Nest/Domain/Responses/GlobalStatsResponse.cs +++ b/src/Nest/Domain/Responses/GlobalStatsResponse.cs @@ -29,6 +29,7 @@ public GlobalStatsResponse() public GlobalStats Stats { get; set; } [JsonProperty(PropertyName = "indices")] + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] public Dictionary Indices { get; set; } } diff --git a/src/Nest/Domain/Responses/HealthResponse.cs b/src/Nest/Domain/Responses/HealthResponse.cs index 5b1930bb5c1..c6da03ccc64 100644 --- a/src/Nest/Domain/Responses/HealthResponse.cs +++ b/src/Nest/Domain/Responses/HealthResponse.cs @@ -53,6 +53,7 @@ public HealthResponse() public int UnassignedShards { get; internal set; } [JsonProperty(PropertyName = "indices")] + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] public Dictionary Indices { get; set; } } } diff --git a/src/Nest/Domain/Responses/MultiSearchResponse.cs b/src/Nest/Domain/Responses/MultiSearchResponse.cs index f44af53219b..444ebc14a10 100644 --- a/src/Nest/Domain/Responses/MultiSearchResponse.cs +++ b/src/Nest/Domain/Responses/MultiSearchResponse.cs @@ -12,7 +12,8 @@ public MultiSearchResponse() { this._Responses = new Dictionary(); } - + + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] internal IDictionary _Responses { get; set; } public IEnumerable> GetResponses() where T : class diff --git a/src/Nest/Domain/Responses/NodeInfoResponse.cs b/src/Nest/Domain/Responses/NodeInfoResponse.cs index 21252631567..5d11885a5b1 100644 --- a/src/Nest/Domain/Responses/NodeInfoResponse.cs +++ b/src/Nest/Domain/Responses/NodeInfoResponse.cs @@ -27,6 +27,7 @@ public NodeInfoResponse() public string ClusterName { get; internal set; } [JsonProperty(PropertyName = "nodes")] - public Dictionary Nodes { get; set; } + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] + public Dictionary Nodes { get; set; } } } diff --git a/src/Nest/Domain/Responses/NodeStatsResponse.cs b/src/Nest/Domain/Responses/NodeStatsResponse.cs index ad13693a381..64616412eb0 100644 --- a/src/Nest/Domain/Responses/NodeStatsResponse.cs +++ b/src/Nest/Domain/Responses/NodeStatsResponse.cs @@ -23,6 +23,7 @@ public NodeStatsResponse() [JsonProperty(PropertyName = "cluster_name")] public string ClusterName { get; internal set; } [JsonProperty(PropertyName = "nodes")] - public Dictionary Nodes { get; set; } + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] + public Dictionary Nodes { get; set; } } } diff --git a/src/Nest/Domain/Responses/QueryResponse.cs b/src/Nest/Domain/Responses/QueryResponse.cs index e3e22e47dde..3652a720f8c 100644 --- a/src/Nest/Domain/Responses/QueryResponse.cs +++ b/src/Nest/Domain/Responses/QueryResponse.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using Nest.Resolvers.Converters; using Newtonsoft.Json; using System.Linq.Expressions; using System; @@ -39,6 +40,7 @@ public QueryResponse() public HitsMetaData Hits { get; internal set; } [JsonProperty(PropertyName = "facets")] + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] public IDictionary Facets { get; internal set; } [JsonProperty(PropertyName = "took")] @@ -171,10 +173,10 @@ public HighlightDocumentDictionary Highlights foreach (var hit in this.Hits.Hits) { - if (!hit.Highlight.Any()) + if (!hit.Highlights.Any()) continue; - dict.Add(hit.Id, hit.Highlight); + dict.Add(hit.Id, hit.Highlights); } return dict; diff --git a/src/Nest/Domain/Responses/ReindexObservable.cs b/src/Nest/Domain/Responses/ReindexObservable.cs index 7e32e54f4b9..5b1f9843113 100644 --- a/src/Nest/Domain/Responses/ReindexObservable.cs +++ b/src/Nest/Domain/Responses/ReindexObservable.cs @@ -5,11 +5,13 @@ namespace Nest public class ReindexObservable : IDisposable, IObservable> where T : class { private ReindexDescriptor _reindexDescriptor; + private readonly IConnectionSettings _connectionSettings; internal IElasticClient CurrentClient { get; set; } internal ReindexDescriptor ReindexDescriptor { get; set; } - public ReindexObservable(IElasticClient client, ReindexDescriptor reindexDescriptor) + public ReindexObservable(IElasticClient client, IConnectionSettings connectionSettings, ReindexDescriptor reindexDescriptor) { + this._connectionSettings = connectionSettings; this._reindexDescriptor = reindexDescriptor; this.CurrentClient = client; } @@ -39,7 +41,8 @@ private void Reindex(IObserver> observer) toIndex.ThrowIfNullOrEmpty("toIndex"); var indexSettings = this.CurrentClient.GetIndexSettings(this._reindexDescriptor._FromIndexName); - var createSettings = new CreateIndexDescriptor(this.CurrentClient.Settings).InitializeUsing(indexSettings.Settings); + var createSettings = new CreateIndexDescriptor(this._connectionSettings) + .InitializeUsing(indexSettings.Settings); var createIndexResponse = this.CurrentClient .CreateIndex(toIndex, (c) => { diff --git a/src/Nest/Domain/Responses/RootVersionInfoResponse.cs b/src/Nest/Domain/Responses/RootVersionInfoResponse.cs new file mode 100644 index 00000000000..9ec0cc6db0a --- /dev/null +++ b/src/Nest/Domain/Responses/RootVersionInfoResponse.cs @@ -0,0 +1,34 @@ +using Newtonsoft.Json; + +namespace Nest +{ + public interface IRootInfoResponse : IResponse + { + bool OK { get; } + string Name { get; } + string Tagline { get; } + ElasticSearchVersionInfo Version { get; } + } + + [JsonObject] + public class RootInfoResponse : BaseResponse, IRootInfoResponse + { + public RootInfoResponse() + { + this.IsValid = true; + } + + [JsonProperty(PropertyName = "ok")] + public bool OK { get; internal set; } + + [JsonProperty(PropertyName = "name")] + public string Name { get; internal set; } + + [JsonProperty(PropertyName = "tagline")] + public string Tagline { get; internal set; } + + [JsonProperty(PropertyName = "version")] + public ElasticSearchVersionInfo Version { get; internal set; } + + } +} \ No newline at end of file diff --git a/src/Nest/Domain/Responses/SegmentsResponse.cs b/src/Nest/Domain/Responses/SegmentsResponse.cs index ccb02ffc93b..9bd04625f34 100644 --- a/src/Nest/Domain/Responses/SegmentsResponse.cs +++ b/src/Nest/Domain/Responses/SegmentsResponse.cs @@ -24,7 +24,8 @@ public SegmentsResponse() [JsonProperty(PropertyName = "_shards")] public ShardsMetaData Shards { get; internal set; } - [JsonProperty(PropertyName = "indices")] + [JsonProperty(PropertyName = "indices")] + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] public Dictionary Indices { get; set; } diff --git a/src/Nest/Domain/Responses/WarmerResponse.cs b/src/Nest/Domain/Responses/WarmerResponse.cs index 9692a2368b4..42b4df6c359 100644 --- a/src/Nest/Domain/Responses/WarmerResponse.cs +++ b/src/Nest/Domain/Responses/WarmerResponse.cs @@ -13,6 +13,7 @@ public interface IWarmerResponse : IResponse [JsonConverter(typeof(WarmerResponseConverter))] public class WarmerResponse : BaseResponse, IWarmerResponse { + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] public Dictionary> Indices { get; internal set; } } diff --git a/src/Nest/Domain/Settings/CustomSimilaritySettings.cs b/src/Nest/Domain/Settings/CustomSimilaritySettings.cs index 18ea0140928..e98577697b3 100644 --- a/src/Nest/Domain/Settings/CustomSimilaritySettings.cs +++ b/src/Nest/Domain/Settings/CustomSimilaritySettings.cs @@ -1,4 +1,6 @@ -namespace Nest.Domain.Settings +using Newtonsoft.Json; + +namespace Nest.Domain.Settings { using System.Collections.Generic; @@ -6,7 +8,8 @@ public class CustomSimilaritySettings { public string Name { get; private set; } public string Type { get; private set; } - public Dictionary SimilarityParameters { get; private set; } + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] + public Dictionary SimilarityParameters { get; private set; } public CustomSimilaritySettings(string name, string type) { diff --git a/src/Nest/Domain/Settings/IndexSettings.cs b/src/Nest/Domain/Settings/IndexSettings.cs index b83db4aba5e..04fc059222f 100644 --- a/src/Nest/Domain/Settings/IndexSettings.cs +++ b/src/Nest/Domain/Settings/IndexSettings.cs @@ -83,12 +83,14 @@ public void TryAdd(string key, object value) this.Add(key, value); } + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] internal Dictionary Settings { get; set; } public AnalysisSettings Analysis { get; internal set; } public IList Mappings { get; internal set; } + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] public Dictionary Warmers { get; internal set; } public SimilaritySettings Similarity { get; set; } diff --git a/src/Nest/Domain/State/ClusterState.cs b/src/Nest/Domain/State/ClusterState.cs index a4629a84a0e..91fa5d1a820 100644 --- a/src/Nest/Domain/State/ClusterState.cs +++ b/src/Nest/Domain/State/ClusterState.cs @@ -15,19 +15,22 @@ public class NodeState public string TransportAddress { get; internal set; } [JsonProperty("attributes")] - public Dictionary Attributes { get; internal set; } + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] + public Dictionary Attributes { get; internal set; } } public class RoutingTableState { [JsonProperty("indices")] - public Dictionary Indices { get; internal set; } + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] + public Dictionary Indices { get; internal set; } } public class IndexRoutingTable { [JsonProperty("shards")] - public Dictionary> Shards { get; internal set; } + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] + public Dictionary> Shards { get; internal set; } } public class RoutingShard @@ -66,7 +69,8 @@ public class MetadataState //public ?? Templates { get; internal set; } [JsonProperty("indices")] - public Dictionary Indices { get; internal set; } + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] + public Dictionary Indices { get; internal set; } } public class MetadataIndexState @@ -75,10 +79,12 @@ public class MetadataIndexState public string State { get; internal set; } [JsonProperty("settings")] - public Dictionary Settings { get; internal set; } + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] + public Dictionary Settings { get; internal set; } [JsonProperty("mappings")] - public Dictionary Mappings { get; internal set; } + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] + public Dictionary Mappings { get; internal set; } //[JsonProperty("aliases")] //public ?? Aliases { get; internal set; } diff --git a/src/Nest/Domain/Stats/GlobalStats.cs b/src/Nest/Domain/Stats/GlobalStats.cs index 303fb680775..a5eace0744d 100644 --- a/src/Nest/Domain/Stats/GlobalStats.cs +++ b/src/Nest/Domain/Stats/GlobalStats.cs @@ -12,6 +12,7 @@ public class GlobalStats : Stats [JsonProperty(PropertyName = "indices")] [Obsolete("since 0.90 this is no longer available as a property of result.Stats use result.Indices directly")] + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] public Dictionary Indices { get; set; } } } diff --git a/src/Nest/Domain/Stats/IndexHealthStats.cs b/src/Nest/Domain/Stats/IndexHealthStats.cs index 3ee5c75f94d..f8cc07398f3 100644 --- a/src/Nest/Domain/Stats/IndexHealthStats.cs +++ b/src/Nest/Domain/Stats/IndexHealthStats.cs @@ -29,6 +29,7 @@ public class IndexHealthStats public int UnassignedShards { get; set; } [JsonProperty(PropertyName = "shards")] + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] public Dictionary Shards { get; set; } } } diff --git a/src/Nest/Domain/Stats/IndexingStats.cs b/src/Nest/Domain/Stats/IndexingStats.cs index 66b07c88bfc..30879119fae 100644 --- a/src/Nest/Domain/Stats/IndexingStats.cs +++ b/src/Nest/Domain/Stats/IndexingStats.cs @@ -26,6 +26,7 @@ public class IndexingStats [JsonProperty(PropertyName = "delete_current")] public int DeleteCurrent { get; set; } [JsonProperty(PropertyName = "types")] + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] public Dictionary Types { get; set; } } } diff --git a/src/Nest/Domain/Stats/NodeInfo.cs b/src/Nest/Domain/Stats/NodeInfo.cs index 24d4351e466..bcde05c2e4a 100644 --- a/src/Nest/Domain/Stats/NodeInfo.cs +++ b/src/Nest/Domain/Stats/NodeInfo.cs @@ -23,7 +23,8 @@ public class NodeInfo [JsonProperty(PropertyName = "settings")] - public Dictionary Settings { get; internal set; } + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] + public Dictionary Settings { get; internal set; } [JsonProperty(PropertyName = "os")] public NodeInfoOS OS { get; internal set; } @@ -35,7 +36,8 @@ public class NodeInfo public NodeInfoJVM JVM { get; internal set; } [JsonProperty(PropertyName = "thread_pool")] - public Dictionary ThreadPool { get; internal set; } + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] + public Dictionary ThreadPool { get; internal set; } [JsonProperty(PropertyName = "network")] public NodeInfoNetwork Network { get; internal set; } diff --git a/src/Nest/Domain/Stats/NodeStats.cs b/src/Nest/Domain/Stats/NodeStats.cs index e31b0061f6b..c53e335f806 100644 --- a/src/Nest/Domain/Stats/NodeStats.cs +++ b/src/Nest/Domain/Stats/NodeStats.cs @@ -19,7 +19,8 @@ public class NodeStats public string Hostname { get; internal set; } [JsonProperty("indices")] - public Dictionary Indices { get; internal set; } + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] + public Dictionary Indices { get; internal set; } [JsonProperty("os")] public OSStats OS { get; internal set; } @@ -31,7 +32,8 @@ public class NodeStats public JVM JVM { get; internal set; } [JsonProperty("thread_pool")] - public Dictionary ThreadPool { get; internal set; } + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] + public Dictionary ThreadPool { get; internal set; } [JsonProperty("network")] public NetworkStats Network { get; internal set; } @@ -231,7 +233,8 @@ public class JVM : UptimeStats [JsonProperty("gc")] public GCOverallStats GC { get; internal set; } [JsonProperty("buffer_pools")] - public Dictionary BufferPools { get; internal set; } + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] + public Dictionary BufferPools { get; internal set; } [JsonObject] public class MemoryStats @@ -253,7 +256,8 @@ public class MemoryStats [JsonProperty("non_heap_committed_in_bytes")] public long NonHeapCommittedInBytes { get; internal set; } [JsonProperty("pools")] - public Dictionary Pools { get; internal set; } + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] + public Dictionary Pools { get; internal set; } [JsonObject] public class JVMPool @@ -290,7 +294,8 @@ public class ThreadStats public class GCOverallStats : GarbageCollectorStats { [JsonProperty("Collectors")] - public Dictionary collectors { get; internal set; } + [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] + public Dictionary collectors { get; internal set; } } [JsonObject] diff --git a/src/Nest/ElasticClient-Aliases.cs b/src/Nest/ElasticClient-Aliases.cs index c0dae0e76d1..b8dcfaa0dfc 100644 --- a/src/Nest/ElasticClient-Aliases.cs +++ b/src/Nest/ElasticClient-Aliases.cs @@ -79,7 +79,7 @@ public IIndicesOperationResponse Swap(AliasParams aliasParam, IEnumerable public IIndicesOperationResponse Alias(string alias) { - var index = this.Settings.DefaultIndex; + var index = this._connectionSettings.DefaultIndex; var q = _createCommand("add", new AliasParams { Index = index, Alias = alias }); return this._Alias(q); } @@ -105,7 +105,7 @@ public IIndicesOperationResponse Alias(string index, IEnumerable aliases /// public IIndicesOperationResponse Alias(IEnumerable aliases) { - var index = this.Settings.DefaultIndex; + var index = this._connectionSettings.DefaultIndex; aliases.Select(a => _createCommand("add", new AliasParams { Index = index, Alias = a })); var q = string.Join(",", aliases); return this._Alias(q); @@ -115,7 +115,7 @@ public IIndicesOperationResponse Alias(IEnumerable aliases) /// public IIndicesOperationResponse RemoveAlias(string alias) { - var index = this.Settings.DefaultIndex; + var index = this._connectionSettings.DefaultIndex; var q = _createCommand("remove", new AliasParams { Index = index, Alias = alias }); return this._Alias(q); } @@ -132,7 +132,7 @@ public IIndicesOperationResponse RemoveAlias(string index, string alias) /// public IIndicesOperationResponse RemoveAlias(IEnumerable aliases) { - var index = this.Settings.DefaultIndex; + var index = this._connectionSettings.DefaultIndex; aliases.Select(a => _createCommand("remove", new AliasParams { Index = index, Alias = a })); var q = string.Join(",", aliases); return this._Alias(q); diff --git a/src/Nest/ElasticClient-Analyze.cs b/src/Nest/ElasticClient-Analyze.cs index e3356a5c38d..338f6c33e9b 100644 --- a/src/Nest/ElasticClient-Analyze.cs +++ b/src/Nest/ElasticClient-Analyze.cs @@ -12,7 +12,7 @@ public partial class ElasticClient /// public IAnalyzeResponse Analyze(string text) { - var index = this.Settings.DefaultIndex; + var index = this._connectionSettings.DefaultIndex; return this._Analyze(new AnalyzeParams() { Index = index }, text); } /// diff --git a/src/Nest/ElasticClient-Bulk.cs b/src/Nest/ElasticClient-Bulk.cs index dc3d080b776..20c95022262 100644 --- a/src/Nest/ElasticClient-Bulk.cs +++ b/src/Nest/ElasticClient-Bulk.cs @@ -31,7 +31,7 @@ public IBulkResponse Bulk(BulkDescriptor bulkDescriptor) var command = operation._Operation; var index = operation._Index ?? bulkDescriptor._FixedIndex ?? - new IndexNameResolver(this.Settings).GetIndexForType(operation._ClrType); + new IndexNameResolver(this._connectionSettings).GetIndexForType(operation._ClrType); var typeName = operation._Type ?? bulkDescriptor._FixedType ?? this.GetTypeNameFor(operation._ClrType); @@ -41,19 +41,19 @@ public IBulkResponse Bulk(BulkDescriptor bulkDescriptor) operation._Type = typeName; operation._Id = id; - var opJson = JsonConvert.SerializeObject(operation, Formatting.None, IndexSerializationSettings); + var opJson = this.Serializer.Serialize(operation, Formatting.None); var action = "{{ \"{0}\" : {1} }}\n".F(command, opJson); sb.Append(action); if (command == "index" || command == "create") { - string jsonCommand = JsonConvert.SerializeObject(operation._Object, Formatting.None, IndexSerializationSettings); + string jsonCommand = this.Serializer.Serialize(operation._Object, Formatting.None); sb.Append(jsonCommand + "\n"); } else if (command == "update") { - string jsonCommand = JsonConvert.SerializeObject(operation.GetBody(), Formatting.None, IndexSerializationSettings); + string jsonCommand = this.Serializer.Serialize(operation.GetBody(), Formatting.None); sb.Append(jsonCommand + "\n"); } } @@ -181,7 +181,7 @@ private string GenerateBulkCommand(IEnumerable @objects, string index, str sb.Append(objectAction); if (command == "index") { - string jsonCommand = JsonConvert.SerializeObject(@object, Formatting.None, IndexSerializationSettings); + string jsonCommand = this.Serializer.Serialize(@object, Formatting.None); sb.Append(jsonCommand + "\n"); } } @@ -220,7 +220,7 @@ private string GenerateBulkCommand(IEnumerable> @objects, s sb.Append(objectAction); if (command == "index") { - string jsonCommand = JsonConvert.SerializeObject(@object.Document, Formatting.None, IndexSerializationSettings); + string jsonCommand = this.Serializer.Serialize(@object.Document, Formatting.None); sb.Append(jsonCommand + "\n"); } } diff --git a/src/Nest/ElasticClient-Count.cs b/src/Nest/ElasticClient-Count.cs index 1b466581a1a..91f141bed27 100644 --- a/src/Nest/ElasticClient-Count.cs +++ b/src/Nest/ElasticClient-Count.cs @@ -43,7 +43,7 @@ public ICountResponse CountAll(Func, BaseQuery> querySelec /// public ICountResponse Count(Func querySelector) { - var index = this.Settings.DefaultIndex; + var index = this._connectionSettings.DefaultIndex; index.ThrowIfNullOrEmpty("Cannot infer default index for current connection."); string path = this.PathResolver.CreateIndexPath(index, "_count"); diff --git a/src/Nest/ElasticClient-CreateIndex.cs b/src/Nest/ElasticClient-CreateIndex.cs index 60681fb25ea..9eca92fa23e 100644 --- a/src/Nest/ElasticClient-CreateIndex.cs +++ b/src/Nest/ElasticClient-CreateIndex.cs @@ -29,7 +29,7 @@ public IIndicesOperationResponse CreateIndex(string index, Func GetFieldSelection(Action> getSelect d._Id.ThrowIfNullOrEmpty("Id on getselector"); - var p = new PathResolver(this.Settings); + var p = new PathResolver(this._connectionSettings); var path = p.CreateGetPath(d); return this._GetFieldSelection(path); } @@ -70,7 +70,7 @@ public T Get(Action> getSelector) where T : class d._Id.ThrowIfNullOrEmpty("Id on getselector"); - var p = new PathResolver(this.Settings); + var p = new PathResolver(this._connectionSettings); var path = p.CreateGetPath(d); return this._Get(path); } diff --git a/src/Nest/ElasticClient-GetFull.cs b/src/Nest/ElasticClient-GetFull.cs index 9b89cb2944d..7a3ddc4e05e 100644 --- a/src/Nest/ElasticClient-GetFull.cs +++ b/src/Nest/ElasticClient-GetFull.cs @@ -60,7 +60,7 @@ public IGetResponse GetFull(Action> getSelector) where T d._Id.ThrowIfNullOrEmpty("Id on getselector"); - var p = new PathResolver(this.Settings); + var p = new PathResolver(this._connectionSettings); var path = p.CreateGetPath(d); return this._GetFull(path); } diff --git a/src/Nest/ElasticClient-Index.cs b/src/Nest/ElasticClient-Index.cs index b2ee31a57b2..fecf381c1b3 100644 --- a/src/Nest/ElasticClient-Index.cs +++ b/src/Nest/ElasticClient-Index.cs @@ -420,7 +420,7 @@ private IIndexResponse _indexToPath(T @object, string path) where T : class { path.ThrowIfNull("path"); - string json = JsonConvert.SerializeObject(@object, Formatting.Indented, IndexSerializationSettings); + string json = this.Serializer.Serialize(@object, Formatting.Indented); var status = this.Connection.PostSync(path, json); return this.ToParsedResponse(status); @@ -428,7 +428,7 @@ private IIndexResponse _indexToPath(T @object, string path) where T : class private Task _indexAsyncToPath(T @object, string path) where T : class { - string json = JsonConvert.SerializeObject(@object, Formatting.None, IndexSerializationSettings); + string json = this.Serializer.Serialize(@object, Formatting.None); var postTask = this.Connection.Post(path, json); return postTask.ContinueWith(t => this.ToParsedResponse(t.Result)); } diff --git a/src/Nest/ElasticClient-MappingIndex.cs b/src/Nest/ElasticClient-MappingIndex.cs index bf8a7b368f2..3cdad56165d 100644 --- a/src/Nest/ElasticClient-MappingIndex.cs +++ b/src/Nest/ElasticClient-MappingIndex.cs @@ -16,7 +16,7 @@ public partial class ElasticClient /// public IIndexSettingsResponse GetIndexSettings() { - var index = this.Settings.DefaultIndex; + var index = this._connectionSettings.DefaultIndex; return this.GetIndexSettings(index); } /// @@ -53,7 +53,7 @@ public IIndexSettingsResponse GetIndexSettings(string index) /// public ISettingsOperationResponse UpdateSettings(IndexSettings settings) { - var index = this.Settings.DefaultIndex; + var index = this._connectionSettings.DefaultIndex; return this.UpdateSettings(index, settings); } /// diff --git a/src/Nest/ElasticClient-MappingType.cs b/src/Nest/ElasticClient-MappingType.cs index b553ec9a681..d2ab440a7e5 100644 --- a/src/Nest/ElasticClient-MappingType.cs +++ b/src/Nest/ElasticClient-MappingType.cs @@ -94,7 +94,7 @@ public IIndicesResponse MapFluent(Func, Roo public IIndicesResponse MapFluent(Func, RootObjectMappingDescriptor> typeMappingDescriptor) where T : class { typeMappingDescriptor.ThrowIfNull("typeMappingDescriptor"); - var d = typeMappingDescriptor(new RootObjectMappingDescriptor(this.Settings)); + var d = typeMappingDescriptor(new RootObjectMappingDescriptor(this._connectionSettings)); var typeMapping = d._Mapping; var indexName = d._IndexName; if (indexName.IsNullOrEmpty()) @@ -109,7 +109,7 @@ public IIndicesResponse MapFluent(Func, RootOb /// public IIndicesResponse Map(RootObjectMapping typeMapping) { - return this.Map(typeMapping, this.Settings.DefaultIndex); + return this.Map(typeMapping, this._connectionSettings.DefaultIndex); } /// /// Verbosely and explicitly map an object using a TypeMapping object, this gives you exact control over the mapping. @@ -122,7 +122,7 @@ public IIndicesResponse Map(RootObjectMapping typeMapping, string index, string var mapping = new Dictionary(); mapping.Add(this.ResolveTypeName(typeMapping.TypeNameMarker), typeMapping); - string map = JsonConvert.SerializeObject(mapping, Formatting.None, SerializationSettings); + string map = this.Serializer.Serialize(mapping, Formatting.None); string path = this.PathResolver.CreateIndexTypePath(index, typeName, "_mapping"); if (ignoreConflicts) path += "?ignore_conflicts=true"; @@ -139,7 +139,7 @@ private RootObjectMapping CreateMapFor(string type, int maxRecursion = 0) whe } private RootObjectMapping CreateMapFor(Type t, string type, int maxRecursion = 0) { - var writer = new TypeMappingWriter(t, type, this.Settings, maxRecursion); + var writer = new TypeMappingWriter(t, type, this._connectionSettings, maxRecursion); var typeMapping = writer.RootObjectMappingFromAttributes(); return typeMapping; } diff --git a/src/Nest/ElasticClient-MultiGet.cs b/src/Nest/ElasticClient-MultiGet.cs index 29142c872f3..dc1f6f753c4 100644 --- a/src/Nest/ElasticClient-MultiGet.cs +++ b/src/Nest/ElasticClient-MultiGet.cs @@ -127,7 +127,7 @@ private ConnectionStatus _multiGetUsingDescriptor(Action mul private IEnumerable MultiGet(IEnumerable ids, string path) where T : class { - var data = @"{{ ""ids"": {0} }}".F(JsonConvert.SerializeObject(ids)); + var data = @"{{ ""ids"": {0} }}".F(this.Serialize(ids)); var response = this.Connection.PostSync(path + "_mget", data); if (response.Result == null) diff --git a/src/Nest/ElasticClient-MultiSearch.cs b/src/Nest/ElasticClient-MultiSearch.cs index 8f58e850e3a..35147df8117 100644 --- a/src/Nest/ElasticClient-MultiSearch.cs +++ b/src/Nest/ElasticClient-MultiSearch.cs @@ -33,7 +33,7 @@ public MultiSearchResponse MultiSearch(MultiSearchDescriptor multiSearchDescript var index = indeces ?? multiSearchDescriptor._FixedIndex ?? - new IndexNameResolver(this.Settings).GetIndexForType(operation._ClrType); + new IndexNameResolver(this._connectionSettings).GetIndexForType(operation._ClrType); var types = operation._Types.HasAny() ? string.Join(",", operation._Types) : null; @@ -44,11 +44,11 @@ public MultiSearchResponse MultiSearch(MultiSearchDescriptor multiSearchDescript typeName = null; //force empty typename so we'll query all types. var op = new { index = index, type = typeName, search_type = this.GetSearchType(operation), preference = operation._Preference, routing = operation._Routing }; - var opJson = JsonConvert.SerializeObject(op, Formatting.None, IndexSerializationSettings); + var opJson = this.Serializer.Serialize(op, Formatting.None); var action = "{0}\n".F(opJson); sb.Append(action); - var searchJson = JsonConvert.SerializeObject(operation, Formatting.None, IndexSerializationSettings); + var searchJson = this.Serializer.Serialize(operation, Formatting.None); sb.Append(searchJson + "\n"); } @@ -62,7 +62,7 @@ public MultiSearchResponse MultiSearch(MultiSearchDescriptor multiSearchDescript } var status = this.Connection.PostSync(path, json); - var multiSearchConverter = new MultiSearchConverter(multiSearchDescriptor); + var multiSearchConverter = new MultiSearchConverter(this._connectionSettings, multiSearchDescriptor); var multiSearchResponse = this.ToParsedResponse(status, extraConverters: new List { diff --git a/src/Nest/ElasticClient-Percolate.cs b/src/Nest/ElasticClient-Percolate.cs index 21d2c130a61..d30c40e11e5 100644 --- a/src/Nest/ElasticClient-Percolate.cs +++ b/src/Nest/ElasticClient-Percolate.cs @@ -96,7 +96,7 @@ private PathAndData _percolate(Func, PercolateDescript var descriptor = percolateSelector(new PercolateDescriptor()); var index = descriptor._Index ?? this.IndexNameResolver.GetIndexForType(); var type = descriptor._Type ?? this.GetTypeNameFor(); - var percolateJson = this.SerializeCamelCase(descriptor); + var percolateJson = this.Serialize(descriptor); var path = this.PathResolver.CreateIndexTypePath(index, type, "_percolate"); return new PathAndData() { Path = path, Data = percolateJson }; diff --git a/src/Nest/ElasticClient-Reindex.cs b/src/Nest/ElasticClient-Reindex.cs index 971e42a2160..5b663cb36a5 100644 --- a/src/Nest/ElasticClient-Reindex.cs +++ b/src/Nest/ElasticClient-Reindex.cs @@ -16,7 +16,7 @@ public IObservable> Reindex(Func, Re reindexSelector.ThrowIfNull("reindexSelector"); var reindexDescriptor = reindexSelector(new ReindexDescriptor()); - var observable = new ReindexObservable(this, reindexDescriptor); + var observable = new ReindexObservable(this, this._connectionSettings, reindexDescriptor); return observable; } diff --git a/src/Nest/ElasticClient-Search.cs b/src/Nest/ElasticClient-Search.cs index d5e56bd3f36..6df494984b1 100644 --- a/src/Nest/ElasticClient-Search.cs +++ b/src/Nest/ElasticClient-Search.cs @@ -160,7 +160,7 @@ private IQueryResponse GetParsedResponse(ConnectionStatus s ) { var typeDictionary = types - .ToDictionary(t => t.Resolve(this.Settings), t => t.Type); + .ToDictionary(t => t.Resolve(this._connectionSettings), t => t.Type); descriptor._ConcreteTypeSelector = (o, h) => { diff --git a/src/Nest/ElasticClient-Statics.cs b/src/Nest/ElasticClient-Statics.cs index a555c277366..3c4d2dbe409 100644 --- a/src/Nest/ElasticClient-Statics.cs +++ b/src/Nest/ElasticClient-Statics.cs @@ -10,100 +10,46 @@ namespace Nest { public partial class ElasticClient { - internal readonly JsonSerializerSettings SerializationSettings; - internal readonly JsonSerializerSettings IndexSerializationSettings; internal readonly PropertyNameResolver PropertyNameResolver; - private readonly List _extraConverters = new List(); - - private readonly List _defaultConverters = new List - { - new IsoDateTimeConverter(), - new FacetConverter() - }; - - private JsonSerializerSettings CreateSettings() - { - return new JsonSerializerSettings() - { - ContractResolver = new ElasticResolver(this.Settings), - NullValueHandling = NullValueHandling.Ignore, - DefaultValueHandling = DefaultValueHandling.Include, - Converters = _defaultConverters.Concat(_extraConverters).ToList() - }; - } - public void AddConverter(JsonConverter converter) + + private string Serialize(object @object) { - this.IndexSerializationSettings.Converters.Add(converter); - this.SerializationSettings.Converters.Add(converter); - _extraConverters.Add(converter); + return this.Serializer.Serialize(@object); } - public void ModifyJsonSerializationSettings(Action modifier) + private T Deserialize(string value, IEnumerable extraConverters = null) { - modifier(this.IndexSerializationSettings); - modifier(this.SerializationSettings); - } - - /// - /// serialize an object using the internal registered converters without camelcasing properties as is done - /// while indexing objects - /// - public string Serialize(object @object) - { - return JsonConvert.SerializeObject(@object, Formatting.Indented, this.SerializationSettings); - } - - /// - /// Serialize an object using the default camelCasing used while indexing objects - /// - public string SerializeCamelCase(object @object) - { - return JsonConvert.SerializeObject(@object, Formatting.Indented, this.IndexSerializationSettings); - } - - /// - /// Deserialize an object - /// - public T Deserialize(string value, IEnumerable extraConverters = null) - { - - var settings = this.SerializationSettings; - if (extraConverters.HasAny()) - { - settings = this.CreateSettings(); - var concrete = extraConverters.OfType().FirstOrDefault(); - if (concrete != null) - { - ((ElasticResolver) settings.ContractResolver).ConcreteTypeConverter = concrete; - } - else - settings.Converters = settings.Converters.Concat(extraConverters).ToList(); - - } - return JsonConvert.DeserializeObject(value, settings); + return this.Serializer.Deserialize(value, extraConverters); } public string GetTypeNameFor() { return GetTypeNameFor(typeof (T)); } + public string GetTypeNameFor(Type type) { - return this.TypeNameResolver.GetTypeNameFor(type).Resolve(this.Settings); + return this.TypeNameResolver.GetTypeNameFor(type).Resolve(this._connectionSettings); } public string GetIndexNameFor() { - return GetIndexName(typeof(T)); + return GetIndexNameFor(typeof(T)); } - public string GetIndexName(Type type) + + public string GetIndexNameFor(Type type) { return this.IndexNameResolver.GetIndexForType(type); } + protected virtual R ToParsedResponse(ConnectionStatus status, bool allow404 = false, IEnumerable extraConverters = null) where R : BaseResponse + { + return this.Serializer.ToParsedResponse(status, allow404, extraConverters); + } + private string ResolveTypeName(TypeNameMarker typeNameMarker, string defaultIndexName = null) { - return typeNameMarker != null ? typeNameMarker.Resolve(this.Settings) : defaultIndexName; + return typeNameMarker != null ? typeNameMarker.Resolve(this._connectionSettings) : defaultIndexName; } } diff --git a/src/Nest/ElasticClient-Template.cs b/src/Nest/ElasticClient-Template.cs index f639c415f63..a6cdd752d5c 100644 --- a/src/Nest/ElasticClient-Template.cs +++ b/src/Nest/ElasticClient-Template.cs @@ -24,7 +24,7 @@ public IIndicesOperationResponse PutTemplate(Func(Action> updateSelecto var updateDescriptor = new UpdateDescriptor(); updateSelector(updateDescriptor); //var data = JsonConvert.SerializeObject(updateDescriptor, Formatting.Indented, IndexSerializationSettings); - var data = this.SerializeCamelCase(updateDescriptor); + var data = this.Serialize(updateDescriptor); var path = this.CreateUpdatePath(updateDescriptor); return this._Update(path, data); } @@ -26,7 +26,7 @@ private string CreateUpdatePath(UpdateDescriptor s) where K : class { var index = s._Index ?? this.IndexNameResolver.GetIndexForType(); - var type = s._Type != null ? s._Type.Resolve(this.Settings) : this.GetTypeNameFor(); + var type = s._Type != null ? s._Type.Resolve(this._connectionSettings) : this.GetTypeNameFor(); var id = s._Id ?? this.IdResolver.GetIdFor(s._Object); index.ThrowIfNullOrEmpty("index"); diff --git a/src/Nest/ElasticClient-Warmers.cs b/src/Nest/ElasticClient-Warmers.cs index f87af0a9086..77d2eab870d 100644 --- a/src/Nest/ElasticClient-Warmers.cs +++ b/src/Nest/ElasticClient-Warmers.cs @@ -13,7 +13,7 @@ public partial class ElasticClient public IIndicesOperationResponse PutWarmer(Func selector) { selector.ThrowIfNull("selector"); - var descriptor = selector(new PutWarmerDescriptor(Settings)); + var descriptor = selector(new PutWarmerDescriptor(_connectionSettings)); descriptor.ThrowIfNull("descriptor"); var query = this.Serialize(descriptor._SearchDescriptor); @@ -31,7 +31,7 @@ public IIndicesOperationResponse PutWarmer(Func selector) { selector.ThrowIfNull("selector"); - var descriptor = selector(new GetWarmerDescriptor(Settings)); + var descriptor = selector(new GetWarmerDescriptor(_connectionSettings)); descriptor.ThrowIfNull("descriptor"); var path = this.PathResolver.GetWarmerPath(descriptor); @@ -46,7 +46,7 @@ public IWarmerResponse GetWarmer(Func public IIndicesOperationResponse DeleteWarmer(Func selector) { selector.ThrowIfNull("selector"); - var descriptor = selector(new GetWarmerDescriptor(Settings)); + var descriptor = selector(new GetWarmerDescriptor(_connectionSettings)); descriptor.ThrowIfNull("descriptor"); var path = this.PathResolver.GetWarmerPath(descriptor); diff --git a/src/Nest/ElasticClient.cs b/src/Nest/ElasticClient.cs index a66a501f873..a7cd1223707 100644 --- a/src/Nest/ElasticClient.cs +++ b/src/Nest/ElasticClient.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Threading.Tasks; using Nest.Resolvers.Converters; using Newtonsoft.Json.Linq; using Newtonsoft.Json; @@ -9,42 +10,15 @@ namespace Nest { public partial class ElasticClient : Nest.IElasticClient { - public IConnection Connection { get; protected set; } - public IConnectionSettings Settings { get; protected set; } - private bool _gotNodeInfo = false; - private bool _IsValid { get; set; } - private ElasticSearchVersionInfo _VersionInfo { get; set; } + private readonly IConnectionSettings _connectionSettings; private TypeNameResolver TypeNameResolver { get; set; } private IdResolver IdResolver { get; set; } private IndexNameResolver IndexNameResolver { get; set; } private PathResolver PathResolver { get; set; } - /// - /// Validates the connection once and returns a bool whether NEST could connect to elasticsearch. - /// - public bool IsValid - { - get - { - if (!this._gotNodeInfo) - this.GetNodeInfo(); - return this._IsValid; - } - } - /// - /// Return the version info that was set when NEST did its one off sanity checks - /// - public IElasticSearchVersionInfo VersionInfo - { - get - { - if (!this._gotNodeInfo) - this.GetNodeInfo(); - return this._VersionInfo; - } - } - + public IConnection Connection { get; protected set; } + public ElasticSerializer Serializer { get; protected set; } public IRawElasticClient Raw { get; private set; } public ElasticClient(IConnectionSettings settings) @@ -52,118 +26,48 @@ public ElasticClient(IConnectionSettings settings) { } + public ElasticClient(IConnectionSettings settings, IConnection connection) { if (settings == null) throw new ArgumentNullException("settings"); - this.Settings = settings; + this._connectionSettings = settings; this.Connection = connection; this.TypeNameResolver = new TypeNameResolver(); this.IdResolver = new IdResolver(); this.IndexNameResolver = new IndexNameResolver(settings); this.PathResolver = new PathResolver(settings); - //this._defaultConverters.Add(new TypeNameMarkerConverter(this.Settings)); - //this._defaultConverters.Add(new IndexSettingsConverter(this.Settings)); - - this.SerializationSettings = this.CreateSettings(); - var indexSettings = this.CreateSettings(); - - indexSettings.ContractResolver = new ElasticCamelCaseResolver(this.Settings); - this.IndexSerializationSettings = indexSettings; this.PropertyNameResolver = new PropertyNameResolver(); - this.Raw = new RawElasticClient(this.Settings, connection); + this.Serializer = new ElasticSerializer(this._connectionSettings); + this.Raw = new RawElasticClient(this._connectionSettings, connection); } - public bool TryConnect(out ConnectionStatus status) - { - try - { - status = this.GetNodeInfo(); - return this.IsValid; - } - catch (Exception e) - { - status = new ConnectionStatus(e); - } - return false; - } - - /// - /// Returns a response of type R based on the connection status without parsing status.Result into R + /// Get the data when you hit the elasticsearch endpoint at the too /// /// - protected virtual R ToResponse(ConnectionStatus status, bool allow404 = false) where R : BaseResponse + public IRootInfoResponse RootNodeInfo() { - var isValid = - (allow404) - ? (status.Error == null - || status.Error.HttpStatusCode == System.Net.HttpStatusCode.NotFound) - : (status.Error == null); - var r = (R)Activator.CreateInstance(typeof(R)); - r.IsValid = isValid; - r.ConnectionStatus = status; - r.PropertyNameResolver = PropertyNameResolver; - return r; + var response = this.Connection.GetSync("/"); + return response.ToParsedResponse(); + } + /// - /// Returns a response of type R based on the connection status by trying parsing status.Result into R + /// Get the data when you hit the elasticsearch endpoint at the too /// /// - public virtual R ToParsedResponse(ConnectionStatus status, bool allow404 = false, IEnumerable extraConverters = null) where R : BaseResponse - { - var isValid = - (allow404) - ? (status.Error == null - || status.Error.HttpStatusCode == System.Net.HttpStatusCode.NotFound) - : (status.Error == null); - if (!isValid) - return this.ToResponse(status, allow404); - - var r = this.Deserialize(status.Result, extraConverters: extraConverters); - r.IsValid = isValid; - r.ConnectionStatus = status; - r.PropertyNameResolver = PropertyNameResolver; - return r; - } - - - private ConnectionStatus GetNodeInfo() + public Task RootNodeInfoAsync() { - ConnectionStatus response = null; - try - { - response = this.Connection.GetSync("/"); - if (response.Success) - { - JObject o = JObject.Parse(response.Result); - if (o["ok"] == null) - { - this._IsValid = false; - return response; - } - - this._IsValid = (bool)o["ok"]; - - JObject version = o["version"] as JObject; - this._VersionInfo = this.Deserialize(version.ToString()); - - this._gotNodeInfo = true; - } - return response; - } - catch (Exception e) - { - this._IsValid = false; - return new ConnectionStatus(e); - } + var response = this.Connection.Get("/"); + return response + .ContinueWith(t => t.Result.ToParsedResponse() as IRootInfoResponse); } - } } diff --git a/src/Nest/ElasticSerializer.cs b/src/Nest/ElasticSerializer.cs new file mode 100644 index 00000000000..f3f2055a999 --- /dev/null +++ b/src/Nest/ElasticSerializer.cs @@ -0,0 +1,130 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Nest.Resolvers; +using Nest.Resolvers.Converters; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; + +namespace Nest +{ + public class ElasticSerializer + { + private readonly IConnectionSettings _settings; + private readonly PropertyNameResolver _propertyNameResolver; + private readonly JsonSerializerSettings _serializationSettings; + + private static readonly ConcurrentBag _extraConverters = new ConcurrentBag(); + private static readonly ConcurrentBag _defaultConverters = new ConcurrentBag + { + new IsoDateTimeConverter(), + new FacetConverter(), + new DictionaryKeysAreNotPropertyNamesJsonConverter() + }; + + public ElasticSerializer(IConnectionSettings settings) + { + this._settings = settings; + this._serializationSettings = this.CreateSettings(); + this._propertyNameResolver = new PropertyNameResolver(); + } + + /// + /// Allows you to adjust the buildin JsonSerializerSettings to your liking + /// + public void ModifyJsonSerializationSettings(Action modifier) + { + modifier(this._serializationSettings); + } + + /// + /// Add a JsonConverter to the build in serialization + /// + public void AddConverter(JsonConverter converter) + { + this._serializationSettings.Converters.Add(converter); + _extraConverters.Add(converter); + } + + /// + /// Returns a response of type R based on the connection status without parsing status.Result into R + /// + /// + protected virtual R ToResponse(ConnectionStatus status, bool allow404 = false) where R : BaseResponse + { + var isValid = + (allow404) + ? (status.Error == null + || status.Error.HttpStatusCode == System.Net.HttpStatusCode.NotFound) + : (status.Error == null); + var r = (R)Activator.CreateInstance(typeof(R)); + r.IsValid = isValid; + r.ConnectionStatus = status; + r.PropertyNameResolver = this._propertyNameResolver; + return r; + } + /// + /// Returns a response of type R based on the connection status by trying parsing status.Result into R + /// + /// + public virtual R ToParsedResponse(ConnectionStatus status, bool allow404 = false, IEnumerable extraConverters = null) where R : BaseResponse + { + var isValid = + (allow404) + ? (status.Error == null + || status.Error.HttpStatusCode == System.Net.HttpStatusCode.NotFound) + : (status.Error == null); + if (!isValid) + return this.ToResponse(status, allow404); + + var r = this.Deserialize(status.Result, extraConverters: extraConverters); + r.IsValid = isValid; + r.ConnectionStatus = status; + r.PropertyNameResolver = this._propertyNameResolver; + return r; + } + + /// + /// serialize an object using the internal registered converters without camelcasing properties as is done + /// while indexing objects + /// + public string Serialize(object @object, Formatting formatting = Formatting.Indented) + { + return JsonConvert.SerializeObject(@object, formatting, this._serializationSettings); + } + + /// + /// Deserialize an object + /// + public T Deserialize(string value, IEnumerable extraConverters = null) + { + + var settings = this._serializationSettings; + if (extraConverters.HasAny()) + { + settings = this.CreateSettings(); + var concrete = extraConverters.OfType().FirstOrDefault(); + if (concrete != null) + { + ((ElasticContractResolver)settings.ContractResolver).ConcreteTypeConverter = concrete; + } + else + settings.Converters = settings.Converters.Concat(extraConverters).ToList(); + + } + return JsonConvert.DeserializeObject(value, settings); + } + private JsonSerializerSettings CreateSettings() + { + return new JsonSerializerSettings() + { + ContractResolver = new ElasticContractResolver(this._settings), + NullValueHandling = NullValueHandling.Ignore, + DefaultValueHandling = DefaultValueHandling.Include, + Converters = _defaultConverters.Concat(_extraConverters).ToList() + }; + } + } +} diff --git a/src/Nest/Exception/ConnectionException.cs b/src/Nest/Exception/ConnectionException.cs new file mode 100644 index 00000000000..015ba6d7151 --- /dev/null +++ b/src/Nest/Exception/ConnectionException.cs @@ -0,0 +1,20 @@ +namespace Nest +{ + public class ConnectionException : System.Exception + { + public int HttpStatusCode { get; private set; } + public string Response { get; private set; } + public ConnectionException(string msg, int statusCode = 500, string response = null) : base(msg) + { + this.HttpStatusCode = statusCode; + this.Response = response; + } + + public ConnectionException(string msg, System.Exception exp, int statusCode = 500, string response = null) + : base(msg, exp) + { + this.HttpStatusCode = statusCode; + this.Response = response; + } + } +} \ No newline at end of file diff --git a/src/Nest/IElasticClient.cs b/src/Nest/IElasticClient.cs index 033b74c6b35..1482cea0efb 100644 --- a/src/Nest/IElasticClient.cs +++ b/src/Nest/IElasticClient.cs @@ -8,10 +8,14 @@ namespace Nest { public interface IElasticClient { - IConnection Connection { get; } - bool IsValid { get; } - IConnectionSettings Settings { get; } + ElasticSerializer Serializer { get; } + IRawElasticClient Raw { get; } + + string GetTypeNameFor(); + string GetTypeNameFor(Type type); + string GetIndexNameFor(); + string GetIndexNameFor(Type type); IIndicesOperationResponse Alias(AliasParams aliasParams); IIndicesOperationResponse Alias(IEnumerable aliases); @@ -23,8 +27,6 @@ public interface IElasticClient IBulkResponse Bulk(Func bulkSelector); IBulkResponse Bulk(BulkDescriptor bulkDescriptor); - - IAnalyzeResponse Analyze(AnalyzeParams analyzeParams, string text); IAnalyzeResponse Analyze(string text); @@ -292,11 +294,9 @@ Task RegisterPercolatorAsync( IIndicesOperationResponse RemoveAliases(IEnumerable aliases); IIndicesOperationResponse Rename(string index, string oldAlias, string newAlias); - IQueryResponse Scroll(string scrollTime, string scrollId); IQueryResponse Scroll(string scrollTime, string scrollId) where T : class; - IQueryResponse Search(Func, SearchDescriptor> searcher); IQueryResponse Search(SearchDescriptor descriptor) where T : class; IQueryResponse Search(Func, SearchDescriptor> searcher) where T : class; @@ -308,17 +308,7 @@ Task RegisterPercolatorAsync( ISegmentsResponse Segments(); ISegmentsResponse Segments(IEnumerable indices); ISegmentsResponse Segments(string index); - - /// - /// serialize an object using the internal registered converters without camelcasing properties as is done - /// while indexing objects - /// - string Serialize(object @object); - - /// - /// Serialize an object using the default camelCasing used while indexing objects - /// - string SerializeCamelCase(object @object); + IIndicesShardResponse Snapshot(); IIndicesShardResponse Snapshot(IEnumerable indices); IIndicesShardResponse Snapshot(string index); @@ -330,7 +320,6 @@ Task RegisterPercolatorAsync( IStatsResponse Stats(IEnumerable indices, StatsParams parameters); IStatsResponse Stats(string index); IIndicesOperationResponse Swap(string alias, IEnumerable oldIndices, IEnumerable newIndices); - bool TryConnect(out ConnectionStatus status); IUnregisterPercolateResponse UnregisterPercolator(string index, string name); IUnregisterPercolateResponse UnregisterPercolator(string name) where T : class; IUpdateResponse Update(Action> updateSelector) where T : class; @@ -339,19 +328,14 @@ IUpdateResponse Update(Action> updateSelector) where K : class; ISettingsOperationResponse UpdateSettings(IndexSettings settings); ISettingsOperationResponse UpdateSettings(string index, IndexSettings settings); - IElasticSearchVersionInfo VersionInfo { get; } IValidateResponse Validate(Action querySelector); IValidateResponse Validate(Action> querySelector) where T : class; + IRootInfoResponse RootNodeInfo(); - string GetTypeNameFor(); - string GetTypeNameFor(Type type); - string GetIndexNameFor(); - string GetIndexName(Type type); - R ToParsedResponse(ConnectionStatus status, bool allow404 = false, IEnumerable extraConverters = null) - where R : BaseResponse; - + Task RootNodeInfoAsync(); + } } diff --git a/src/Nest/Nest.csproj b/src/Nest/Nest.csproj index fcc9d32fe08..c2c8464354f 100644 --- a/src/Nest/Nest.csproj +++ b/src/Nest/Nest.csproj @@ -70,6 +70,9 @@ + + + @@ -488,6 +491,7 @@ + @@ -535,7 +539,7 @@ - + diff --git a/src/Nest/Properties/InternalsVisibleTo.cs b/src/Nest/Properties/InternalsVisibleTo.cs index 616b70af4d2..696a95c06c2 100644 --- a/src/Nest/Properties/InternalsVisibleTo.cs +++ b/src/Nest/Properties/InternalsVisibleTo.cs @@ -15,6 +15,7 @@ using System.Runtime.InteropServices; [assembly: InternalsVisibleTo("Nest.Tests.Unit")] [assembly: InternalsVisibleTo("Nest.Tests.Integration")] +[assembly: InternalsVisibleTo("Nest.Connection.Thrift")] [assembly: InternalsVisibleTo("ProtocolLoadTest")] diff --git a/src/Nest/RawElasticClient.cs b/src/Nest/RawElasticClient.cs index 24e7ddb3c6f..c26cfbd5338 100644 --- a/src/Nest/RawElasticClient.cs +++ b/src/Nest/RawElasticClient.cs @@ -13,8 +13,9 @@ namespace Nest { public partial class RawElasticClient : IRawElasticClient { - protected IConnection Connection { get; set; } + public IConnection Connection { get; protected set; } public IConnectionSettings Settings { get; protected set; } + public ElasticSerializer Serializer { get; protected set; } public RawElasticClient(IConnectionSettings settings) : this(settings, new Connection(settings)) @@ -22,49 +23,6 @@ public RawElasticClient(IConnectionSettings settings) } - internal readonly JsonSerializerSettings SerializationSettings; - internal readonly JsonSerializerSettings IndexSerializationSettings; - internal readonly PropertyNameResolver PropertyNameResolver; - private readonly List _extraConverters = new List(); - - private readonly List _defaultConverters = new List - { - new IsoDateTimeConverter(), - new FacetConverter() - }; - - private JsonSerializerSettings CreateSettings() - { - return new JsonSerializerSettings() - { - ContractResolver = new ElasticResolver(this.Settings), - NullValueHandling = NullValueHandling.Ignore, - DefaultValueHandling = DefaultValueHandling.Include, - Converters = _defaultConverters.Concat(_extraConverters).ToList() - }; - } - public void AddConverter(JsonConverter converter) - { - this.IndexSerializationSettings.Converters.Add(converter); - this.SerializationSettings.Converters.Add(converter); - _extraConverters.Add(converter); - } - - public void ModifyJsonSerializationSettings(Action modifier) - { - modifier(this.IndexSerializationSettings); - modifier(this.SerializationSettings); - } - - /// - /// serialize an object using the internal registered converters without camelcasing properties as is done - /// while indexing objects - /// - public string Serialize(object @object) - { - return JsonConvert.SerializeObject(@object, Formatting.Indented, this.SerializationSettings); - } - public RawElasticClient(IConnectionSettings settings, IConnection connection) { if (settings == null) @@ -72,12 +30,12 @@ public RawElasticClient(IConnectionSettings settings, IConnection connection) this.Settings = settings; this.Connection = connection; + this.Serializer = new ElasticSerializer(this.Settings); + } - this.SerializationSettings = this.CreateSettings(); - var indexSettings = this.CreateSettings(); - - indexSettings.ContractResolver = new ElasticCamelCaseResolver(this.Settings); - this.IndexSerializationSettings = indexSettings; + public string Serialize(object @object) + { + return this.Serializer.Serialize(@object); } protected ConnectionStatus DoRequest(string method, string path, object data = null, NameValueCollection queryString = null) diff --git a/src/Nest/Resolvers/Converters/ConcreteTypeConverter.cs b/src/Nest/Resolvers/Converters/ConcreteTypeConverter.cs index 0cd2e9409e7..b36fd50b046 100644 --- a/src/Nest/Resolvers/Converters/ConcreteTypeConverter.cs +++ b/src/Nest/Resolvers/Converters/ConcreteTypeConverter.cs @@ -32,7 +32,7 @@ public ConcreteTypeConverter(Type baseType, Func, Type> co public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { - var realConcreteConverter = ((ElasticResolver) serializer.ContractResolver).ConcreteTypeConverter; + var realConcreteConverter = ((ElasticContractResolver) serializer.ContractResolver).ConcreteTypeConverter; if (realConcreteConverter != null) { diff --git a/src/Nest/Resolvers/Converters/DictionaryKeysAreNotPropertyNamesJsonConverter.cs b/src/Nest/Resolvers/Converters/DictionaryKeysAreNotPropertyNamesJsonConverter.cs new file mode 100644 index 00000000000..8cbcf034923 --- /dev/null +++ b/src/Nest/Resolvers/Converters/DictionaryKeysAreNotPropertyNamesJsonConverter.cs @@ -0,0 +1,45 @@ +using System; +using System.Collections; +using System.Globalization; +using Newtonsoft.Json; + +namespace Nest +{ + /// + /// JSON converter for IDictionary that ignores the contract resolver (e.g. CamelCasePropertyNamesContractResolver) + /// when converting dictionary keys to property names. + /// + public class DictionaryKeysAreNotPropertyNamesJsonConverter : JsonConverter + { + public override bool CanConvert(Type objectType) + { + return typeof(IDictionary).IsAssignableFrom(objectType); + } + + public override bool CanRead + { + get { return false; } + } + + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + throw new InvalidOperationException(); + } + + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + IDictionary dictionary = (IDictionary) value; + + writer.WriteStartObject(); + + foreach (DictionaryEntry entry in dictionary) + { + string key = Convert.ToString(entry.Key, CultureInfo.InvariantCulture); + writer.WritePropertyName(key); + serializer.Serialize(writer, entry.Value); + } + + writer.WriteEndObject(); + } + } +} \ No newline at end of file diff --git a/src/Nest/Resolvers/Converters/IndexNameMarkerConverter.cs b/src/Nest/Resolvers/Converters/IndexNameMarkerConverter.cs index 698d603a7d6..d0f2283bc0d 100644 --- a/src/Nest/Resolvers/Converters/IndexNameMarkerConverter.cs +++ b/src/Nest/Resolvers/Converters/IndexNameMarkerConverter.cs @@ -23,7 +23,7 @@ public override void WriteJson(JsonWriter writer, object value, JsonSerializer s return; } - var settings = serializer.ContractResolver as ElasticResolver; + var settings = serializer.ContractResolver as ElasticContractResolver; if (settings != null && settings.ConnectionSettings != null) { var typeName = marker.Resolve(settings.ConnectionSettings); diff --git a/src/Nest/Resolvers/Converters/IndexSettingsConverter.cs b/src/Nest/Resolvers/Converters/IndexSettingsConverter.cs index bf0f0c7b05d..db60aadaf23 100644 --- a/src/Nest/Resolvers/Converters/IndexSettingsConverter.cs +++ b/src/Nest/Resolvers/Converters/IndexSettingsConverter.cs @@ -105,7 +105,7 @@ public override void WriteJson(JsonWriter writer, object value, JsonSerializer s writer.WriteEndObject(); if (indexSettings.Mappings.Count > 0) { - var settings = serializer.ContractResolver as ElasticResolver; + var settings = serializer.ContractResolver as ElasticContractResolver; if (settings != null && settings.ConnectionSettings != null) { writer.WritePropertyName("mappings"); diff --git a/src/Nest/Resolvers/Converters/MultiSearchConverter.cs b/src/Nest/Resolvers/Converters/MultiSearchConverter.cs index ac987c38694..54a0c75ea66 100644 --- a/src/Nest/Resolvers/Converters/MultiSearchConverter.cs +++ b/src/Nest/Resolvers/Converters/MultiSearchConverter.cs @@ -20,9 +20,11 @@ private class MultiHitTuple private readonly MultiSearchDescriptor _descriptor; private static MethodInfo MakeDelegateMethodInfo = typeof(MultiSearchConverter).GetMethod("CreateMultiHit", BindingFlags.Static | BindingFlags.NonPublic); + private readonly IConnectionSettings _settings; - public MultiSearchConverter(MultiSearchDescriptor descriptor) + public MultiSearchConverter(IConnectionSettings settings, MultiSearchDescriptor descriptor) { + this._settings = settings; _descriptor = descriptor; } @@ -30,7 +32,13 @@ public override void WriteJson(JsonWriter writer, object value, JsonSerializer s { throw new NotSupportedException(); } - private static void CreateMultiHit(MultiHitTuple tuple, JsonSerializer serializer, IDictionary collection) where T : class + private static void CreateMultiHit( + MultiHitTuple tuple, + JsonSerializer serializer, + IDictionary collection, + IConnectionSettings settings + ) + where T : class { var hit = new QueryResponse(); var reader = tuple.Hit.CreateReader(); @@ -40,7 +48,10 @@ private static void CreateMultiHit(MultiHitTuple tuple, JsonSerializer serial if (errorProperty != null) { hit.IsValid = false; - hit.ConnectionStatus = new ConnectionStatus(new ConnectionError(errorProperty.Value.ToString(), 500)); + hit.ConnectionStatus = new ConnectionStatus(settings, new ConnectionException( + msg: errorProperty.Value.ToString(), + response: errorProperty.Value.ToString() + )); } collection.Add(tuple.Descriptor.Key, hit); @@ -63,7 +74,7 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist foreach (var m in withMeta) { var generic = MakeDelegateMethodInfo.MakeGenericMethod(m.Descriptor.Value._ClrType); - generic.Invoke(null, new object[] { m, serializer, response._Responses }); + generic.Invoke(null, new object[] { m, serializer, response._Responses, this._settings }); } return response; diff --git a/src/Nest/Resolvers/Converters/TermConverter.cs b/src/Nest/Resolvers/Converters/TermConverter.cs index c44c353fb37..c388e28995f 100644 --- a/src/Nest/Resolvers/Converters/TermConverter.cs +++ b/src/Nest/Resolvers/Converters/TermConverter.cs @@ -54,3 +54,4 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist } } + diff --git a/src/Nest/Resolvers/Converters/TypeNameMarkerConverter.cs b/src/Nest/Resolvers/Converters/TypeNameMarkerConverter.cs index 7d233021b6e..4a1e8dfb33e 100644 --- a/src/Nest/Resolvers/Converters/TypeNameMarkerConverter.cs +++ b/src/Nest/Resolvers/Converters/TypeNameMarkerConverter.cs @@ -22,7 +22,7 @@ public override void WriteJson(JsonWriter writer, object value, JsonSerializer s writer.WriteNull(); return; } - var settings = serializer.ContractResolver as ElasticResolver; + var settings = serializer.ContractResolver as ElasticContractResolver; if (settings != null && settings.ConnectionSettings != null) { var typeName = marker.Resolve(settings.ConnectionSettings); diff --git a/src/Nest/Resolvers/ElasticSearchJsonResolver.cs b/src/Nest/Resolvers/ElasticContractResolver.cs similarity index 72% rename from src/Nest/Resolvers/ElasticSearchJsonResolver.cs rename to src/Nest/Resolvers/ElasticContractResolver.cs index ab8f6207795..57a3afd0005 100644 --- a/src/Nest/Resolvers/ElasticSearchJsonResolver.cs +++ b/src/Nest/Resolvers/ElasticContractResolver.cs @@ -10,7 +10,7 @@ namespace Nest.Resolvers { - public class ElasticResolver : DefaultContractResolver + public class ElasticContractResolver : DefaultContractResolver { /// /// ConnectionSettings can be requested by JsonConverter's. @@ -23,11 +23,19 @@ public class ElasticResolver : DefaultContractResolver /// internal ConcreteTypeConverter ConcreteTypeConverter { get; set; } - public ElasticResolver(IConnectionSettings connectionSettings) : base(true) + public ElasticContractResolver(IConnectionSettings connectionSettings) : base(true) { this.ConnectionSettings = connectionSettings; } + protected override string ResolvePropertyName(string propertyName) + { + if (this.ConnectionSettings.DefaultPropertyNameInferrer != null) + return this.ConnectionSettings.DefaultPropertyNameInferrer(propertyName); + + return propertyName.ToCamelCase(); + } + protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) { var property = base.CreateProperty(member, memberSerialization); @@ -43,22 +51,6 @@ protected override JsonProperty CreateProperty(MemberInfo member, MemberSerializ property.Ignored = att.OptOut; return property; } - protected override string ResolvePropertyName(string propertyName) - { - return base.ResolvePropertyName(propertyName); - } - public string Resolve(string name) - { - return this.ResolvePropertyName(name); - } - } - public class ElasticCamelCaseResolver : ElasticResolver - { - public ElasticCamelCaseResolver(IConnectionSettings connectionSettings) : base(connectionSettings) { } - protected override string ResolvePropertyName(string propertyName) - { - return propertyName.ToCamelCase(); - } } } diff --git a/src/Nest/Resolvers/Writers/TypeMappingWriter.cs b/src/Nest/Resolvers/Writers/TypeMappingWriter.cs index 843cf5286fc..1323c0f6aef 100644 --- a/src/Nest/Resolvers/Writers/TypeMappingWriter.cs +++ b/src/Nest/Resolvers/Writers/TypeMappingWriter.cs @@ -14,7 +14,8 @@ internal class TypeMappingWriter { private readonly Type _type; private readonly PropertyNameResolver _propertyNameResolver = new PropertyNameResolver(); - private readonly IConnectionSettings _connectionSettings; + private readonly IConnectionSettings _connectionSettings; + private readonly ElasticSerializer _elasticSerializer; private int MaxRecursion { get; set; } private TypeNameMarker TypeName { get; set; } @@ -30,6 +31,8 @@ public TypeMappingWriter(Type t, TypeNameMarker typeName, IConnectionSettings co this.SeenTypes = new ConcurrentDictionary(); this.SeenTypes.TryAdd(t, 0); + + this._elasticSerializer = new ElasticSerializer(this._connectionSettings); } internal TypeMappingWriter(Type t, string typeName, IConnectionSettings connectionSettings, int maxRecursion, ConcurrentDictionary seenTypes) { @@ -39,6 +42,8 @@ internal TypeMappingWriter(Type t, string typeName, IConnectionSettings connecti this.TypeName = typeName; this.MaxRecursion = maxRecursion; this.SeenTypes = seenTypes; + + this._elasticSerializer = new ElasticSerializer(this._connectionSettings); } internal JObject MapPropertiesFromAttributes() @@ -67,21 +72,21 @@ internal RootObjectMapping RootObjectMappingFromAttributes() var json = JObject.Parse(this.MapFromAttributes()); var nestedJson = json.Properties().First().Value.ToString(); - return JsonConvert.DeserializeObject(nestedJson); + return this._elasticSerializer.Deserialize(nestedJson); } internal ObjectMapping ObjectMappingFromAttributes() { var json = JObject.Parse(this.MapFromAttributes()); var nestedJson = json.Properties().First().Value.ToString(); - return JsonConvert.DeserializeObject(nestedJson); + return this._elasticSerializer.Deserialize(nestedJson); } internal NestedObjectMapping NestedObjectMappingFromAttributes() { var json = JObject.Parse(this.MapFromAttributes()); var nestedJson = json.Properties().First().Value.ToString(); - return JsonConvert.DeserializeObject(nestedJson); + return this._elasticSerializer.Deserialize(nestedJson); } internal string MapFromAttributes() { diff --git a/src/ProtocolLoadTest/Connection/AsyncRequestOperation.cs b/src/ProtocolLoadTest/Connection/AsyncRequestOperation.cs index a7b89c36d43..f4566814e31 100644 --- a/src/ProtocolLoadTest/Connection/AsyncRequestOperation.cs +++ b/src/ProtocolLoadTest/Connection/AsyncRequestOperation.cs @@ -91,7 +91,7 @@ private void Done(Stream result) { result.Position = 0; var reader = new StreamReader(result); - Done(new ConnectionStatus(reader.ReadToEnd()) + Done(new ConnectionStatus(this.m_connectionSettings, reader.ReadToEnd()) { Request = this.m_requestData, RequestUrl = this.m_request.RequestUri.ToString(), @@ -110,7 +110,7 @@ private AsyncCallback Monitor(AsyncCallback callback) } catch (WebException webException) { - var connectionStatus = new ConnectionStatus(webException) + var connectionStatus = new ConnectionStatus(this.m_connectionSettings, webException) { Request = this.m_requestData, RequestUrl = this.m_request.RequestUri.ToString(), diff --git a/src/ProtocolLoadTest/Program.cs b/src/ProtocolLoadTest/Program.cs index 364ce81515f..1d980a59e29 100644 --- a/src/ProtocolLoadTest/Program.cs +++ b/src/ProtocolLoadTest/Program.cs @@ -82,12 +82,11 @@ private static void RecreateIndex(string suffix) var client = new ElasticClient(connSettings); - ConnectionStatus connStatus; - - if (!client.TryConnect(out connStatus)) + var result = client.RootNodeInfo(); + if (!result.IsValid) { Console.Error.WriteLine("Could not connect to {0}:\r\n{1}", - connSettings.Host, connStatus.Error.OriginalException.Message); + connSettings.Host, result.ConnectionStatus.Error.OriginalException.Message); Console.Read(); return; } @@ -116,12 +115,11 @@ private static void CloseIndex(string suffix) var client = new ElasticClient(connSettings); - ConnectionStatus connStatus; - - if (!client.TryConnect(out connStatus)) + var result = client.RootNodeInfo(); + if (!result.IsValid) { Console.Error.WriteLine("Could not connect to {0}:\r\n{1}", - connSettings.Host, connStatus.Error.OriginalException.Message); + connSettings.Host, result.ConnectionStatus.Error.OriginalException.Message); Console.Read(); return; } diff --git a/src/ProtocolLoadTest/Tester.cs b/src/ProtocolLoadTest/Tester.cs index a780c22aa15..3aba07d5af8 100644 --- a/src/ProtocolLoadTest/Tester.cs +++ b/src/ProtocolLoadTest/Tester.cs @@ -26,14 +26,12 @@ protected ConnectionSettings CreateSettings(string indexName, int port) protected void Connect(ElasticClient client, ConnectionSettings settings) { - ConnectionStatus indexConnectionStatus; - - if (!client.TryConnect(out indexConnectionStatus)) + var result = client.RootNodeInfo(); + if (!result.IsValid) { Console.Error.WriteLine("Could not connect to {0}:\r\n{1}", - settings.Host, indexConnectionStatus.Error.OriginalException.Message); + settings.Host, result.ConnectionStatus.Error.OriginalException.Message); Console.Read(); - return; } }