3

I ma making my first steps using ElasticSearch and NEST C# library for .NET. Here is my code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Nest;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        var setting = new ConnectionSettings(new Uri("http://localhost:9200/"));
        setting.SetDefaultIndex("Post");
        var client = new ElasticClient(setting);

        var post = new Post();
        post.id = 1;
        post.title = "the title";

        var t = client.Index(post);

        var results = client.Search<Post>(s => s.From(0)
            .Size(10)
            .Fields(f => f.id, f => f.title)
            .Query(q => q.Term(f => f.title, "title", Boost: 2.0))
            );

    }
}
public class Post
{
    public int id { get; set; }
    public string title { get; set; }
}

I was expecting to get the result from Post 1 because it has "title" keyword in it, but I get empty result set. What I am doing wrong?

1

2 Answers 2

3

The issue is the term query being used. This will only match the exact text indexed. The term query is useful for id type searching.

If you are doing free text searching try using the match query for a good general purpose free text search. You can read more about it here on the official docs and hopefully start discovering how to build interesting and powerful queries by becoming familiar with the docs.

Good luck

Sign up to request clarification or add additional context in comments.

Comments

0

It takes a very little time for the indexation of your Post. If you insert a Thread.Sleep(1000); between your indexation and your query, you'll have results.

2 Comments

While this is a good spot (and I certainly was confused by this at one point) I think it might be the type of query he is using.
If you need to get results immediately after an Index() use Get() which is realtime or if you need to get it back from the Search() call Index() passing new IndexParameters { Refresh = true } but in the long run you gain more from designing the app to deal with the Near Real Time nature of elasticsearch. Never ever rely on a Thread.Sleep for a plethora of reasons.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.