Contenu connexe Similaire à Mecanismo de busca .NET Core + MongoDB (20) Mecanismo de busca .NET Core + MongoDB3. Ciência da Computação
Computação Móvel
Dev, analista, gerente...
11 anos programando
- 7 anos com mecanismos de busca
- 3 buscadores no ar
- inúmeros projetos
23. MongoDB
Carga de dados:
use searchengine
custArray = [{"Nome":"Luiz Júnior", "Profissao":"Professor",
"Tags":["LUIZ","JUNIOR","PROFESSOR"]}, {"Nome":"Luiz
Fernando", "Profissao":"Autor", "Tags":
["LUIZ","FERNANDO","AUTOR"]}, {"Nome":"Luiz Tools",
"Profissao":"Blogueiro", "Tags":
["LUIZ","TOOLS","BLOGUEIRO"]}, {"Nome":"Luiz Duarte",
"Profissao":"Blogueiro", "Tags":
["LUIZ","DUARTE","BLOGUEIRO"]}]
db.Customer.insert(custArray);
33. .NET Core
customizando shared/_Layout.cshtml:
<li><a asp-area="" asp-controller="Home" asp-action="Search">Search</a></li>
customizando Views/Home/Search.cshtml:
<div class="row" style="margin-top: 20px">
<form method="GET" action="/Home/Search">
<p><label>Pesquisa: <input type="text" name="q" /></label></p>
<p><input type="submit" value="Pesquisar" class="btn btn-primary" /></p>
</form>
</div>
36. .NET Core
customizando Models/Customer.cs:
public class Customer
{
[BsonId]
public ObjectId Id { get; set; }
[BsonRequired]
[BsonElement("Nome")]
public string Nome { get; set; }
public string Profissao { get; set; }
public List<string> Tags { get; set; }
}
37. .NET Core
customizando Models/DataAccess.cs:
public class DataAccess
{
MongoClient _client;
IMongoDatabase _db;
public DataAccess()
{
_client = new MongoClient("mongodb://localhost:27017");
_db = _client.GetDatabase("searchengine");
}
public long CountCustomers(){
return _db.GetCollection<Customer>(typeof(Customer).Name).Count(new
FilterDefinitionBuilder<Customer>().Empty);
}
38. .NET Core
Teste para ver se funciona:
// HomeController.cs
public IActionResult Search()
{
ViewData["Message"] = "Search page.";
ViewData["Count"] = new DataAccess().CountCustomers();
return View();
}
<!-- Search.cshtml -->
<p>@Html.Raw(ViewData["Count"]) clientes cadastrados!</p>
40. .NET Core
customizando Models/DataAccess.cs:
public IEnumerable<Customer> GetCustomers(string query)
{
var tags = query.ToUpper().Split(new string[] { " " },
StringSplitOptions.RemoveEmptyEntries).ToList();
var filter = Builders<Customer>.Filter.All(c => c.Tags, tags);
return
_db.GetCollection<Customer>(typeof(Customer).Name).Find(filter).ToList();
}
41. .NET Core
customizando HomeController.cs:
public IActionResult Search(String q)
{
ViewData["Message"] = "Search page.";
var da = new DataAccess();
ViewData["Count"] = da.CountCustomers();
if(!String.IsNullOrEmpty(q))
{
return View(da.GetCustomers(q));
}
return View();
}