本文整理汇总了C#中Nest.ElasticClient.Index方法的典型用法代码示例。如果您正苦于以下问题:C# ElasticClient.Index方法的具体用法?C# ElasticClient.Index怎么用?C# ElasticClient.Index使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Nest.ElasticClient
的用法示例。
在下文中一共展示了ElasticClient.Index方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GenerateLookupDocumentLists
public static void GenerateLookupDocumentLists(ElasticClient client)
{
foreach (var skill in SampleDatasets.SkillsCollection)
client.Index(skill);
foreach (var cert in SampleDatasets.CertificationCollection)
client.Index(cert);
}
示例2: Main
static void Main(string[] args)
{
elasticSettings = new ConnectionSettings(new Uri("http://127.0.0.1:9200"))
.SetDefaultIndex("people");
client = new ElasticClient(elasticSettings);
client.DeleteIndex("people");
// Create an index
client.CreateIndex("people", c => c
.NumberOfReplicas(0)
.NumberOfShards(1));
client.MapFluent<Person>(m => m.IndexAnalyzer("standard")
.Properties(props => props
.String(s => s
.Name(p => p.Message)
.Index(FieldIndexOption.analyzed))
.Number(n => n
.Name(p => p.Age))
.String(s => s
.Name(p => p.FirstName))
.String(s => s
.Name(p => p.Sex))
.String(s => s
.Name(p => p.LastName))));
//Add some people
var jp = new Person { FirstName = "JP", LastName = "Smith", Age = 37, Message = "OMG yay ES!", Sex = "Male" };
var matt = new Person { FirstName = "Matt", LastName = "Toto", Age = 32, Message = "I'm JPs brother", Sex = "Male" };
var christine = new Person { FirstName = "Christine", LastName = "Toto", Age = 0, Message = "I'm JPs wife", Sex = "Female" };
var kevin = new Person { FirstName = "Kevin", LastName = "Toto", Age = 26, Message = "I'm JPs other brother", Sex = "Male" };
client.Index(jp);
client.Index(matt);
client.Index(christine);
client.Index(kevin);
client.Refresh();
///// ** Wildcard search
var searchResults = client.Search<Person>(s => s
.From(0)
.Size(10)
.Query(q => q
.Wildcard(f => f.LastName, "to*", Boost: 1.0)
)
);
foreach (var result in searchResults.Documents)
{
Console.WriteLine("Found: {0}", result.FirstName + " " + result.LastName);
}
Console.ReadKey();
}
示例3: RebuildIndex
public void RebuildIndex(string userId, int? noteId)
{
if (!string.IsNullOrWhiteSpace(userId))
{
var notes = new List<NoteModel>();
if (noteId.HasValue)
notes.Add(Repository.GetById(noteId.Value));
else
notes = Repository.GetByUserId(userId).ToList();
var settings = new ConnectionSettings(new Uri("http://localhost:9200"), "mapnotes");
var client = new ElasticClient(settings);
var indexExists = client.IndexExists("mapnotes");
if (!indexExists.Exists)
{
client.CreateIndex(descriptor => descriptor.Index("mapnotes")
.AddMapping<NoteIndex>(m => m.Properties(p => p.GeoPoint(d => d.Name(f => f.Location).IndexLatLon()))));
}
foreach (var note in notes)
{
client.Index(new NoteIndex
{
Id = note.Id,
UserId = note.UserId,
Title = note.Title,
Location = new Location(note.Latitude, note.Longitude)
});
}
}
}
示例4: Main
static void Main(string[] args)
{
var context = new ElasticDBEntities();
var artists = context.Artists.ToList();
var node = "http://localhost:9200";
var searchBoxUri = new Uri(node);
var settings = new ConnectionSettings(searchBoxUri);
//settings.SetDefaultIndex("sample");
var client = new ElasticClient(settings);
if (client.IndexExists("store").Exists)
{
client.DeleteIndex("store");
}
//client.CreateIndex("sample");
foreach (var artist in artists)
{
//var index = client.Index(artist);
var index = client.Index(artist, i => i.Index("store").Refresh());
}
// Index all documents
//client.IndexMany<Artist>(artists);
}
示例5: Append
/// <summary>
/// Add a log event to the ElasticSearch Repo
/// </summary>
/// <param name="loggingEvent"></param>
protected override void Append(Core.LoggingEvent loggingEvent)
{
if (string.IsNullOrEmpty(ConnectionString))
{
var exception = new InvalidOperationException("Connection string not present.");
ErrorHandler.Error("Connection string not included in appender.", exception, ErrorCode.GenericFailure);
return;
}
client = new ElasticClient(ConnectionBuilder.BuildElsticSearchConnection(ConnectionString));
LogEvent logEvent = new LogEvent();
if (logEvent == null)
{
throw new ArgumentNullException("logEvent");
}
logEvent.LoggerName = loggingEvent.LoggerName;
logEvent.Domain = loggingEvent.Domain;
logEvent.Identity = loggingEvent.Identity;
logEvent.ThreadName = loggingEvent.ThreadName;
logEvent.UserName = loggingEvent.UserName;
logEvent.MessageObject = loggingEvent.MessageObject == null ? "" : loggingEvent.MessageObject.ToString();
logEvent.TimeStamp = loggingEvent.TimeStamp;
logEvent.Exception = loggingEvent.ExceptionObject == null ? "" : loggingEvent.MessageObject.ToString();
logEvent.Message = loggingEvent.RenderedMessage;
logEvent.Fix = loggingEvent.Fix.ToString();
if (loggingEvent.Level != null)
{
logEvent.Level = loggingEvent.Level.DisplayName;
}
if (loggingEvent.LocationInformation != null)
{
logEvent.ClassName = loggingEvent.LocationInformation.ClassName;
logEvent.FileName = loggingEvent.LocationInformation.FileName;
logEvent.LineNumber = loggingEvent.LocationInformation.LineNumber;
logEvent.FullInfo = loggingEvent.LocationInformation.FullInfo;
logEvent.MethodName = loggingEvent.LocationInformation.MethodName;
}
logEvent.Properties = loggingEvent.Properties.GetKeys().ToDictionary(key => key, key => logEvent.Properties[key].ToString());
if (client.IsValid)
{
var results = client.Index(logEvent);
}
else
{
var exception = new InvalidOperationException("Connection to ElasticSearch is invalid.");
ErrorHandler.Error("Invalid connection to ElasticSearch", exception, ErrorCode.GenericFailure);
return;
}
}
示例6: GetMessages
public IEnumerable<Message> GetMessages()
{
client = this.Connect();
foreach (var m in messages)
{
client.Index(m);
}
return messages;
}
示例7: foreach
async Task IEventProcessor.ProcessEventsAsync(PartitionContext context, IEnumerable<EventData> messages)
{
try
{
foreach (EventData eventData in messages)
{
var data = Encoding.UTF8.GetString(eventData.GetBytes());
var items = data.Split(new string[]{"##"}, StringSplitOptions.None);
var apiManagementLogEvent = new ApiManagementLogEvent
{
Timestamp = Convert.ToDateTime(items[0]),
ServiceName = items[1],
UserId = items[2],
Region = items[3],
RequestId = items[4],
IpAddress = items[5],
Operation = items[6],
Status = items[7],
Body = items[8]
};
//Console.WriteLine(items[8]);
var esnode = new Uri(Constants.ElasticsearchUrl);
var settings = new ConnectionSettings(
esnode, "apim-" + DateTime.Now.ToString("yyyy.MM.dd")
);
var client = new ElasticClient(settings);
client.Index(apiManagementLogEvent);
}
//Call checkpoint every 5 minutes, so that worker can resume processing from the 5 minutes back if it restarts.
if (this.checkpointStopWatch.Elapsed > TimeSpan.FromMinutes(5))
{
await context.CheckpointAsync();
this.checkpointStopWatch.Restart();
}
}
catch (Exception e)
{
Trace.Listeners.Add(new TextWriterTraceListener(Console.Out)); Trace.WriteLine(e.InnerException);
}
}
示例8: UpsertContact
public static void UpsertContact(ElasticClient client, Contacts contact)
{
var RecordInserted = client.Index(contact);
if (RecordInserted.ToString() != "")
{
Console.WriteLine("Indexing Successful !");
}
else
{
Console.WriteLine("Transaction Failed");
}
}
示例9: GenerateRandomEmployeeDocuments
public static string GenerateRandomEmployeeDocuments(ElasticClient client, string namesDbPath)
{
var db = new SQLiteConnection(namesDbPath);
var female = db.Table<female>().ToList();
var surname = db.Table<surname>().ToList();
var rng = new Random();
const int numEmployeesToCreate = 300;
var numSkillsGenerated = 0;
var numCertsGenerated = 0;
for (var i = 0; i <= numEmployeesToCreate; i++)
{
var emp = new EmployeeSkillsDocument()
{
Id = i,
FirstName = female[rng.Next(0, female.Count - 1)].name,
LastName = surname[rng.Next(0, surname.Count - 1)].name,
Skills = new List<Skill>(),
Certifications = new List<Certification>()
};
for (var j = 0; j <= 10; j++)
{
var candidate = SampleDatasets.SkillsCollection[rng.Next(0, SampleDatasets.SkillsCollection.Count - 1)];
if (!emp.Skills.Contains(candidate))
{
emp.Skills.Add(candidate);
numSkillsGenerated++;
}
}
var numCerts = rng.Next(1, 10);
for (var k = 0; k <= numCerts; k++)
{
var candidate = SampleDatasets.CertificationCollection[rng.Next(0, SampleDatasets.CertificationCollection.Count - 1)];
if (!emp.Certifications.Contains(candidate))
{
emp.Certifications.Add(candidate);
numCertsGenerated++;
}
}
client.Index(emp);
}
return string.Format("Created {0} employee records with {1} skills and {2} certs in index '{3}'",
numEmployeesToCreate, numSkillsGenerated, numCertsGenerated, EsIndexName);
}
示例10: blogMigration
//Migration blog
public static bool blogMigration(ElasticClient elastic)
{
using (var context = new YoupDEVEntities())
{
var blogs = (from b in context.BLOG_Blog
select b).ToList<BLOG_Blog>();
foreach (var blog in blogs)
{
Blog blogElastic = new Blog(blog.Blog_id.ToString(), blog.TitreBlog, blog.Theme_id.ToString());
var indexB = elastic.Index(blogElastic);
/* var visits = (from v in context.BLOG_Visite
where v.Blog_Id == blog.Blog_id
select v).Count();*/
var articles = (from a in context.BLOG_Article
where a.Blog_id == blog.Blog_id
select a).ToList<BLOG_Article>();
foreach (var article in articles)
{
BlogPost articleElastic = new BlogPost(article.Article_id.ToString(), article.ContenuArticle, blog.Utilisateur_id.ToString(), article.TitreArticle);
var indexA = elastic.Index(articleElastic);
var comments = (from c in context.BLOG_Commentaire
where c.Article_id == article.Article_id
select c).ToList<BLOG_Commentaire>();
foreach (var comment in comments)
{
BlogPostComment commentElastic = new BlogPostComment(comment.Commentaire_id.ToString(), comment.ContenuCommentaire, comment.Utilisateur_id.ToString());
var indexBPC = elastic.Index(commentElastic);
}
}
}
}
return true;
}
示例11: Can_insert_data
public void Can_insert_data()
{
using (var elasticsearch = new Elasticsearch())
{
////Arrange
var client = new ElasticClient(new ConnectionSettings(elasticsearch.Url));
////Act
client.Index(new { id = "tester"}, i => i.Index("test-index"));
////Assert
var result = client.Get<dynamic>("tester", "test-index");
Assert.That(result, Is.Not.Null);
}
}
示例12: CreateDocument
public HttpResponseMessage CreateDocument(FormDataCollection postData)
{
SampleConfiguration config = new SampleConfiguration();
esNode = new Uri(config.ElasticsearchServerHost);
connectionSettings = new ConnectionSettings(esNode, defaultIndex: postData.Get("indexName"));
esClient = new ElasticClient(connectionSettings);
var product = new Product(Convert.ToInt32(postData.Get("id")),
postData.Get("title"),
postData.Get("brand"),
Convert.ToDouble(postData.Get("price")));
IIndexResponse indexResponse = esClient.Index(product);
return Request.CreateResponse(HttpStatusCode.Created, indexResponse.Created);
}
示例13: Execute
public void Execute()
{
if (TranslationMemories == null)
throw new ArgumentNullException("No data to import, please set TranslationMemories property first.");
// create client connection
var node = new Uri(ServerUrl);
var conn = new ConnectionSettings(node, this.IndexName);
var client = new ElasticClient(conn);
foreach (TranslationMemory tm in TranslationMemories)
{
var indexResult = client.Index(tm);
Console.Write(indexResult);
}
}
示例14: Main
/// <summary>
/// Mainly used to profile the serialization performance and memory usage
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
var settings = new ConnectionSettings(new Uri("http://localhost:9200"),"test-index");
var client = new ElasticClient(settings);
int calls = 10000;
Console.WriteLine("done");
Console.ReadLine();
//using (var pbar = new ProgressBar(ticks, "Doing loads of in memory calls"))
{
for (int i = calls; i > 0; i--)
{
client.Index(new Doc() {Id = "asdasd" + i, Name = "Repository"});
}
}
Console.WriteLine("done");
Console.ReadLine();
}
示例15: ElasticSearchTest
private static void ElasticSearchTest()
{
var node = new Uri("http://localhost:9200");
var settings = new ConnectionSettings(
node,
defaultIndex: "my-application"
);
var client = new ElasticClient(settings);
Product product = new Product("Tv", DateTime.Now, 200, new string[] { "45''", "48''" });
var index = client.Index(product);
ISearchResponse<Product> searchResults = client.Search<Product>(s => s.MatchAll());
Product prd = searchResults.Hits.FirstOrDefault().Source;
}