Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Tip

쿼리 DSL은 ORM에 있어서도, 검색엔진을 사용하는 검색 쿼리 사용에 있어서도

복잡한 검색기능을 단순하게 구현 하기위한 좋은 방법중에 하나이며

닷넷 어플리케이션내에서 DSL검색 방식을 사용하기에 적합한 NEST를 선택하였습니다.

설정

주요 Nuget 의존성 라이브러리

Code Block
<PackageReference Include="NEST" Version="7.5.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.2.3" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="2.2.0" />

...

App 설정

Code Block
themeEmacs
titleappsetting.json
linenumberstrue
collapsetrue
{
  "Logging": {
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  },
  "AppSettings": {
    "DBConnection": "server=localhost;port=13306;database=search;user=root;password=root;"
  },
  "elasticsearch": {
    "index": "baseitem",
    "url": "http://localhost:9200/"
  }
}


엘라서틱 Config

Code Block
themeEmacs
linenumberstrue
collapsetrue
using System;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Nest;
using SearchApi.Entity;

namespace SearchApi.Config
{
    public static class ElasticsearchExtensions
    {
        public static void AddElasticsearch(
            this IServiceCollection services, IConfiguration configuration)
        {
            var url = configuration["elasticsearch:url"];
            var defaultIndex = configuration["elasticsearch:index"];

            var settings = new ConnectionSettings(new Uri(url))
                .DefaultIndex(defaultIndex)
                .DefaultMappingFor<SearchGoods>(m => m
                    .PropertyName(p => p.no, "id")
                );
            var client = new ElasticClient(settings);
            services.AddSingleton<IElasticClient>(client);
        }
    }
}


StartUp 설정

Code Block
themeEmacs
titleStartup.cs
linenumberstrue
collapsetrue
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddElasticsearch(Configuration);
.......


검색 기능 추가

검색 Entity정의

Code Block
themeEmacs
collapsetrue
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace SearchApi.Entity
{
    [Table("tbl_search_goods")]
    public class SearchGoods
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int no { get; set; }

        [Column("goods_no")]        
        public string goodsNo { get; set; }

        [Column("name_kr")]
        public string nameKr { get; set; }

        [Column("name_en")]
        public string nameEn { get; set; }

        public string category1 { get; set; }

        public string category2 { get; set; }

        public string category3 { get; set; }

        public int price { get; set; }

        [Column("view_cnt")]
        public int viewCnt { get; set; }

        [Column("sale_cnt")]
        public int saleCnt { get; set; }

        public string terms { get; set; }

        public string tags { get; set; }

        [Column("url_pc")]
        public string urlPc { get; set; }

        [Column("url_mobile")]
        public string urlMobile { get; set; }

        [Column("image_url1")]
        public string imageUrl1 { get; set; }

        [Column("image_url2")]
        public string imageUrl2 { get; set; }
    }
}

...

검색엔진의 문서의 검색 속성을 일치화할것입니다. 

검색 Repository for RDB

Code Block
themeEmacs
linenumberstrue
collapsetrue
using System;
using Microsoft.EntityFrameworkCore;
using SearchApi.Config;
using SearchApi.Entity;


namespace SearchApi.Repositories
{
    public class SearchRepository : DbContext
    {
        private const string database = "search";
        
        private readonly AppSettings appSettings;

        private readonly bool isEncript;
        
        public string DebugConString { get; set; }

        public DbSet<SearchGoods> searchGoods { get; set; }

        public SearchRepository(DbContextOptions<SearchRepository> options,
            AppSettings _appSettings) : base(options)
        {
            appSettings = _appSettings;            
            if (!appSettings.DBConnection.Contains("localhost"))
            {
                isEncript = true;
            }
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                string dbOption = "";
                string dbConnectionString = string.Empty;
                if (isEncript)
                {
                    throw new NotImplementedException("암호화 모듈을 적용하시오~");
                }
                else
                {
                    dbConnectionString = appSettings.DBConnection + $"database={database};" + dbOption;
                }                
                optionsBuilder.UseMySql(dbConnectionString);
            }
        }
    }
}

...

Link : https://docs.microsoft.com/en-us/ef/core/


DI를 통한 엘라서틱 서치 클라이언트 사용

Code Block
themeEmacs
using Microsoft.AspNetCore.Mvc;
using Nest;

namespace SearchApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class TestController : ControllerBase
    {
        private readonly IElasticClient _elasticClient;

        public TestController(IElasticClient elasticClient)
        {            
            _elasticClient = elasticClient;
        }     
    }
}

...