Синонимы не работают в клиенте C #asticSearch? - PullRequest
0 голосов
/ 23 мая 2018

я разрабатываю простое приложение winformsApp, которое будет искать из базы данных, используяasticSearch.поиск и синоним tokenfilter работали нормально, когда мой файлasticSearchClient.cs находился в том же проекте, что и проект winformsApp.Однако, когда я сделал отдельный проект, который включает в себя тот же файлasticSearchClient.cs, фильтр токенов синонимов перестал работать.хотя поиск по-прежнему работает нормально.

Я прикреплю код-позади winformsApp и код клиента-эластичного поиска ниже.Мой вопрос: как я могу заставить работать синонимы, когда клиент winformsapp иasticsearch размещен в двух разных проектах?или какие последовательные шаги отладки я могу предпринять, чтобы узнать точное положение ошибки?спасибо

файлasticSearchClient.cs:

using Elasticsearch.Net;
using Nest;
using Newtonsoft.Json;
using System;
using System.Configuration;
using System.Threading.Tasks;
using Nest.JsonNetSerializer;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json.Serialization;
using SynonymSearch.ElasticSearch;


namespace NESTClient.ElasticSearch
{
    public class ElasticSearchClient : ElasticSearchClientBase
    {
        public const string synonymsindexname = "synonyms";
        public const string WORDNETSYNONYMFILEPATH = "synonyms/WNprolog-3.0/prolog/wn_s.pl";

        #region Constructors
        public ElasticSearchClient()
            : base()
        {
            ConnectionSettings.DefaultMappingFor<ClinicalCode>(m => m
            );
        }
        #endregion

        #region Overrides

        public override string Username
        {
            get
            {

                return ConfigurationManager.AppSettings["ElasticSearchUsername"];

            }
        }


        public override string Password
        {
            get
            {

                return ConfigurationManager.AppSettings["ElasticSearchPassword"];
            }
        }


        public override string ElasticSearchUrl
        {
            get
            {

                string elasticSearchUrl = ConfigurationManager.AppSettings["ElasticSearchUrl"];
                if (string.IsNullOrEmpty(elasticSearchUrl))

                    return "http://localhost.:9200"; 
                else
                    return elasticSearchUrl;
            }
        }

        public override ConnectionSettings InitializeConnectionSettings(string elasticSearchUrl)
        {
            var pool = new SingleNodeConnectionPool(new Uri(elasticSearchUrl));
            var connection = new HttpConnection();

            var connectionSettings = new ConnectionSettings(
                pool,
                connection: connection,

                sourceSerializer: (builtin, settings) => new NestJsonNetSerializer(builtin, settings)

            );


            if (string.IsNullOrEmpty(Username) == false && string.IsNullOrEmpty(Password))
                connectionSettings = connectionSettings.BasicAuthentication(Username, Password);
            return connectionSettings;
        }
        #endregion

        #region Index Creation(s)

        public void CreatesynonymsIndex()
        {
            Task task = CreatesynonymsIndexAsync();
            task.Wait();
        }


        public async Task CreatesynonymsIndexAsync()
        {

            if (Client.IndexExists(synonymsindexname).Exists)
            {
                var deleteIndexTask = Client.DeleteIndexAsync(synonymsindexname);
                await deleteIndexTask;
                if (deleteIndexTask.Result.IsValid == false)
                {
                    var serverError = deleteIndexTask.Result.ServerError;
                    throw new Exception(string.Format("{0}: {1}", serverError.Status, serverError.Error));
                }
            }


            **var createIndexTask = Client.CreateIndexAsync(synonymsindexname, i => i
                .Settings(s => s
                    .Analysis(a => a
                         .TokenFilters(t => t



                            .Stop("my_english_stop", st => st
                                .IgnoreCase()
                                .StopWords("_english_")
                            )

                            .Synonym("my_synonyms", syn => syn

                                    // .Format(SynonymFormat.WordNet)
                                    // .SynonymsPath(WORDNETSYNONYMFILEPATH)

                                    .Tokenizer("lowercase")
                                    .Format(SynonymFormat.Solr)
                              //.Synonyms(
                               //   "cholera, colera"
                             //    "typhoid, tyfoid",
                             //    "shigellosis, shigelosys abc"

                             // )
                             .SynonymsPath("synonyms/solrsynonyms.txt")

                            )
                        )
                        .Analyzers(aa => aa



                            .Standard("standard_english", sa => sa
                                .StopWords("_english_")
                            )

                           .Custom("my_synonym2", c => c


                              .Tokenizer("standard")



                              .Filters("lowercase", "my_synonyms", "test", "standard", "my_english_stop")
                           )

                        )

                    )
                )

                .Mappings(m => m
                    .Map<ClinicalCode>(c => c

                        .AutoMap()

                        .Properties(p => p

                            .Keyword(k => k
                                .Name(n => n.ICDCode)

                            )
                            .Text(t => t
                                .Name(n => n.ShortDescription)
                                .Name(n => n.LongDescription)
                                .Analyzer("my_synonym2")

                            )
                            .Text(t => t
                                .Name(n => n.ShortDescription)
                                .Name(n => n.LongDescription)
                                .Analyzer("standard_english")
                            )
                            .Text(t => t
                                .Name(n => n.ShortDescription)
                                .Name(n => n.LongDescription)
                                .Analyzer("english")
                            )
                            .Text(t => t
                                .Name(n => n.ShortDescription)
                                .Name(n => n.LongDescription)
                                .Analyzer("simple")
                            )
                            .Completion(com => com
                                .Name(n => n.ShortDescription)
                            )
                        )
                    )
                ) 
            );**



            await createIndexTask;
            var result = createIndexTask.Result;
            if (createIndexTask.Result.IsValid == false)
            {
                var serverError = createIndexTask.Result.ServerError;
                throw new Exception(string.Format("{0}: {1}", serverError.Status, serverError.Error));
            }
        }
        #endregion
    }


    public class NestJsonNetSerializer : ConnectionSettingsAwareSerializerBase 
    {
        public NestJsonNetSerializer(IElasticsearchSerializer builtinSerializer, IConnectionSettingsValues connectionSettings)
            : base(builtinSerializer, connectionSettings) { }

        protected override IEnumerable<JsonConverter> CreateJsonConverters() =>
            Enumerable.Empty<JsonConverter>();

        protected override JsonSerializerSettings CreateJsonSerializerSettings() =>
            new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Include,
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            };
    }

}

файл form1.cs:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Nest;
using SynonymSearch.ElasticSearch;
using NESTClient.ElasticSearch;


namespace ServerWinforms
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            ElasticSearchClient searchClient = new ElasticSearchClient();

            PerformDeleteIndex();
            PerformCreateIndex();
            PerformSearchIndexing();

            PerformGettingAllItems();


        }

        private void button1_Click(object sender, EventArgs e)
        {

            string query = textBox1.Text;
            //MessageBox.Show("hola");


            ElasticSearchClient searchClient = new ElasticSearchClient();
            ISearchResponse<ClinicalCode> response = null;

            response = searchClient.Client.Search<ClinicalCode>(x => x  
                .Index(ElasticSearchClient.synonymsindexname)
                .Query(q => q               
                    .MultiMatch(mp => mp            
                        .Query(query)           
                       // .Fuzziness(Fuzziness.Auto) 
                        .Fields(fs => fs
                            .Field(f => f.ICDCode) 
                            .Field(f => f.ShortDescription) 
                            .Field(f => f.LongDescription)


                        )

                    )   
                )
                .Highlight(h => h 
                    .PreTags("<mark class='hit'>")
                    .PostTags("</mark>")
                    .Fields(fs => fs
                        .Field("*")
                        .RequireFieldMatch(false) 
                    )
                )
                .From(0)                
                .Size(30)               
            );

            if (response.IsValid == false) 
            {
                MessageBox.Show(response.DebugInformation);
            }
            else
            {
                StringBuilder sb = new StringBuilder();

                    IEnumerable<IHit<ClinicalCode>> synonymsHits = response.Hits.OrderBy(x => x.Source.ICDCode).ThenBy(x => x.Source.ShortDescription).ThenBy(x => x.Source.LongDescription);
                    foreach (IHit<ClinicalCode> synonymsHit in synonymsHits)
                    {

                        HighlightFieldDictionary highlightFieldDictionary = synonymsHit.Highlights;

                        if (highlightFieldDictionary.ContainsKey("ICDCode"))
                            sb.AppendLine(string.Format("ICDCode:       {0}", highlightFieldDictionary["ICDCode"].Highlights.First())); 
                        else
                            sb.AppendLine(string.Format("ICDCode:       {0}", synonymsHit.Source.ICDCode));

                        if (highlightFieldDictionary.ContainsKey("ShortDescription"))
                            sb.AppendLine(string.Format("ShortDescription:       {0}", highlightFieldDictionary["ShortDescription"].Highlights.First()));
                        else
                            sb.AppendLine(string.Format("ShortDescription:       {0}", synonymsHit.Source.ShortDescription));

                        if (highlightFieldDictionary.ContainsKey("LongDescription"))
                            sb.AppendLine(string.Format("LongDescription:       {0}", highlightFieldDictionary["LongDescription"].Highlights.First()));
                        else
                            sb.AppendLine(string.Format("LongDescription:       {0}", synonymsHit.Source.LongDescription));


                        sb.AppendLine();
                        sb.AppendLine();
                    }

                textBox2.Text = sb.ToString();




            }



        }
        private void label1_Click(object sender, EventArgs e)
        {


        }

        public static void PerformDeleteIndex()
        {

                ElasticSearchClient searchClient = new ElasticSearchClient();

                var deleteTask = searchClient.Client.DeleteIndexAsync(ElasticSearchClient.synonymsindexname);

        }

        public static void PerformCreateIndex()
        {       

                ElasticSearchClient searchClient = new ElasticSearchClient();

                var createTask = searchClient.CreatesynonymsIndexAsync();

        }

        public static void PerformSearchIndexing()
        {

                List<ClinicalCode> synonymslist = ClinicalCode.GetAllsynonymslist(); 

                ElasticSearchClient searchClient = new ElasticSearchClient();                

                int batchSize = 100; 
                int maxParallelExecution = 10; 
                IndexByChunkSettings chunkSettings = new IndexByChunkSettings(batchSize, maxParallelExecution);
                chunkSettings.Index = ElasticSearchClient.synonymsindexname;
                var synonymsIndexingTask = searchClient.Client.IndexManyByChunkAsync(synonymslist, chunkSettings);            

        }

        public static void PerformGettingAllItems()
        {


            ElasticSearchClient searchClient = new ElasticSearchClient();
            ISearchResponse<ClinicalCode> response = null;

            response = searchClient.Client.Search<ClinicalCode>(s => s
                .Index(ElasticSearchClient.synonymsindexname)
                .From(0)
                .Take(20)
            );                       
        }



    }
}
...