developer machine 에서 Elastic 검색을 설정하는 방법과 .net 애플리케이션에서 Elastic 과 통신하는 방법을 보여드리겠습니다. 나는 기사에서 아래의 요점을 다룰 것입니다.
public class ElasticSearchClient
{
#region Elasticsearch Connection
public ElasticClient EsClient()
{
var nodes = new Uri[]
{
new Uri("http://localhost:9200/"),
};
var connectionPool = new StaticConnectionPool(nodes);
var connectionSettings = new ConnectionSettings(connectionPool).DisableDirectStreaming();
var elasticClient = new ElasticClient(connectionSettings.DefaultIndex("productdetails"));
return elasticClient;
}
#endregion Elasticsearch Connection
}
색인에 문서를 삽입하기 위한 모델 및 컨트롤러를 추가합니다.
public class Products
{
public int ProductId { get; set; }
public string ProductName { get; set; }
public decimal Price { get; set; }
public string Description { get; set; }
public List<CheckBoxModel> Colors { get; set; }
public List<CheckBoxModel> Tags { get; set; }
}
public class CheckBoxModel
{
public int Value { get; set; }
public string Text { get; set; }
public bool IsChecked { get; set; }
}
public class ProductController : Controller
{
private readonly ElasticSearchClient _esClient;
public ProductController()
{
_esClient = new ElasticSearchClient();
}
// GET: Product
public ActionResult Index()
{
return RedirectToAction("Create");
}
// GET: Product/Create
public ActionResult Create()
{
var colors = new List<CheckBoxModel>()
{
new CheckBoxModel {Value=1,Text="Red",IsChecked=true },
new CheckBoxModel {Value=1,Text="Green",IsChecked=false },
new CheckBoxModel {Value=1,Text="Orange",IsChecked=false },
new CheckBoxModel {Value=1,Text="Blue" ,IsChecked=false},
new CheckBoxModel {Value=1,Text="Purple",IsChecked=false },
new CheckBoxModel {Value=1,Text="Yellow" ,IsChecked=false},
};
var tags = new List<CheckBoxModel>()
{
new CheckBoxModel {Value=1,Text="Mens wear",IsChecked=true },
new CheckBoxModel {Value=1,Text="Ladies Wear",IsChecked=false },
new CheckBoxModel {Value=1,Text="New Arraival",IsChecked=false },
new CheckBoxModel {Value=1,Text="Top Brands" ,IsChecked=false},
new CheckBoxModel {Value=1,Text="Kids Wear",IsChecked=false },
new CheckBoxModel {Value=1,Text="Jeans" ,IsChecked=false},
};
var productDetails = new Products
{
Colors = colors,
Tags = tags
};
return View(productDetails);
}
// POST: Product/Create
[HttpPost]
public ActionResult Create(Products products)
{
try
{
var productDetail = new ProductDetails()
{
ProductId = products.ProductId,
ProductName = products.ProductName,
Price = products.Price,
Description = products.Description,
Colors = products.Colors.Where(x => x.IsChecked == true).Select(x => x.Text).ToArray(),
Tags = products.Tags.Where(x => x.IsChecked == true).Select(x => x.Text).ToArray()
};
// Insert product detail document to index
var defaultIndex = "productdetails";
var indexExists = _esClient.EsClient().Indices.Exists(defaultIndex);
if (!indexExists.Exists)
{
var response = _esClient.EsClient().Indices.Create(defaultIndex,
index => index.Map<ProductDetails>(
x => x.AutoMap()
));
}
var indexResponse1 = _esClient.EsClient().IndexDocument(productDetail);
return RedirectToAction("Create");
}
catch
{
return View();
}
}
}
아래 화면을 사용하여 색인에 제품을 추가하십시오. 여기 이 화면에서 10개의 제품을 추가했습니다.
제품 추가 화면에서 삽입된 인덱스에 현재 아래의 레코드가 있습니다.
[{
"productId": 1,
"productName": "Shirt",
"price": 1000.0,
"description": "Shirt is made from pure cotton. Very stylish shirt specially designed for men.",
"colors": [
"Red",
"Green",
"Orange",
"Purple",
"Yellow"
],
"tags": [
"Mens wear",
"New Arraival"
]
},
{
"productId": 2,
"productName": "Pures",
"price": 1200.0,
"description": "Hand made purse for Women. Designed from pure leather.",
"colors": [
"Red",
"Green",
"Purple",
"Yellow"
],
"tags": [
"New Arraival",
"Top Brands"
]
},
{
"productId": 3,
"productName": "Jacket",
"price": 1300.0,
"description": "Jackat is made from leather. specially designed for men and womens",
"colors": [
"Red",
"Green",
"Orange",
"Yellow"
],
"tags": [
"New Arraival",
"Top Brands"
]
},
{
"productId": 4,
"productName": "Blazer",
"price": 1400.0,
"description": "Hand made blazer which are very stylish and specially designed for man.",
"colors": [
"Red",
"Green",
"Orange",
"Blue",
"Purple",
"Yellow"
],
"tags": [
"Mens wear",
"Ladies Wear",
"New Arraival",
"Top Brands"
]
},
{
"productId": 5,
"productName": "Jeans Top",
"price": 1400.0,
"description": "Jeans is for men and women. Very good quality material with latest design",
"colors": [
"Blue"
],
"tags": [
"Mens wear",
"Ladies Wear",
"New Arraival",
"Jeans"
]
},
{
"productId": 6,
"productName": "Girl Dresses",
"price": 1500.0,
"description": "Girl dresses and casual wears",
"colors": [
"Red",
"Orange",
"Purple"
],
"tags": [
"Top Brands",
"Kids Wear"
]
},
{
"productId": 7,
"productName": "Jumpsuits",
"price": 500.0,
"description": "Girl jumpsuit with latest design",
"colors": [
"Orange",
"Blue",
"Purple"
],
"tags": [
"New Arraival",
"Top Brands",
"Kids Wear",
"Jeans"
]
},
{
"productId": 8,
"productName": "Kurta",
"price": 1700.0,
"description": "Men traditional and designer kurta with latest design",
"colors": [
"Red",
"Green",
"Orange",
"Purple",
"Yellow"
],
"tags": [
"Mens wear",
"New Arraival",
"Top Brands"
]
},
{
"productId": 9,
"productName": "chididar",
"price": 1400.0,
"description": "Ladies chudidar dress with quality fabric.",
"colors": [
"Red",
"Green",
"Orange",
"Blue",
"Purple",
"Yellow"
],
"tags": [
"Ladies Wear",
"New Arraival",
"Top Brands"
]
},
{
"productId": 10,
"productName": "Purse",
"price": 600.0,
"description": "Purse is made from pure leather. 100% pure leather is used to make this purse with great finishing.",
"colors": [
"Red",
"Green",
"Orange",
"Blue",
"Purple",
"Yellow"
],
"tags": [
"Ladies Wear",
"Top Brands"
]
}
]
이제 elastic 인덱스에서 데이터 검색을 위한 코드 스니펫을 추가해 보겠습니다.
public class ProductDetails
{
public int ProductId { get; set; }
public string ProductName { get; set; }
public decimal Price { get; set; }
public string Description { get; set; }
public string[] Colors { get; set; }
public string[] Tags { get; set; }
}
public class SearchController : Controller
{
private readonly ElasticSearchClient _esClient;
public SearchController()
{
_esClient = new ElasticSearchClient();
}
[HttpGet]
public ActionResult Search()
{
return View("Search");
}
public JsonResult DataSearch(string term)
{
var responsedata = _esClient.EsClient().Search<ProductDetails>(s => s.Source()
.Query(q => q
.QueryString(qs => qs
.AnalyzeWildcard()
.Query("*" + term.ToLower() + "*")
.Fields(fs => fs
.Fields(f1 => f1.ProductName,
f2 => f2.Description,
f3 => f3.Tags,
f4 => f4.Colors
)
)
)));
var datasend = responsedata.Documents.ToList();
return Json(datasend, behavior: JsonRequestBehavior.AllowGet);
}
}
이제 한 가지 예를 더 들어보겠습니다. "men"라는 용어로 검색하십시오. 이 단어는 아래 문서에 존재하므로 아래와 같이 6개의 문서를 반환합니다.
이제 색상 열로 검색해 보겠습니다. yellow 를 검색해 봤습니다.
"Top Brand"라는 용어가 포함된 태그 열에 대한 시나리오를 한 번 더 검색해 보겠습니다.