Versions Compared

Key

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

...

설정

주요 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" />

...

추후 대량의 배치처리시 ORM의 성능 문제가 된다고 하면, 배치성능에 최적화된 ORM 확장 모듈을 사용할수도 있습니다. 

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);
            }
        }
    }
}


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

Code Block
themeEmacs
collapsetrue
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;
        }     
    }
}







참고링크: