Semant1ka
Semant1ka

Reputation: 687

NEST search through all available objects

I've started writing a small utility for Elasticsearch using NEST and have no previous experience with Elastic API. Though I've tried to do my research I've stumbled with a few simple lines of code and can't understand how they supposed to work.

What I want to do: just look for an object with a specific field value. For example, I'll take modified Person class from Quick Start Guide

  public class Person
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string FavoriteColor {get; set; }
        public string TimeAdded {get; set; }
    }

I have index people_dd_mm_yyy, so I can't set default index because it updates every day.

Also, I don't have a single idea which people will be in the index, so I just want to look through, let's say, people added today and find all people who love colour red.

        var p = new Person();
        var indexResponse = client.Index(p,s => s.Index("people_*"));
        var search = client.Search<Person>(s => s
        .From(0)
        .Size(10)
        .Query(q => q
        .Match(m => m
        .Field(f => f.FavoriteColor)
        .Query("Red"))));

Search won't find anything because all fields will be empty in search documents. How do I just index all objects regardless of their content? Okay, I know I want all objects to have FavoriteColor = Red, so I can write

 var p = new Person() { FavoriteColor = "Red"};

but I have no idea what other fields will be, how do I make Elastic fill them in in response?

Seems I can't understand the idea of indexing and searching engine in Elastic.

I think I am trying to do body search but the example with this request on github also requires me to know everything about the object I want to search.

Upvotes: 0

Views: 359

Answers (1)

Marcus H&#246;glund
Marcus H&#246;glund

Reputation: 16846

First, If you want to search on multiple indexces you should specify it in the query like (check this great post)

client.Search<Person>(s => s
        .Index("people_*")...

Secondly, If you are interested in finding all persons where the favorit color is red, I would use Term instead of Match. Term will make a filtering on Red while Match will make a Full Text Search and look for occurrences for Red in fields. If I would explain this as easy as possible I would compare them to SQL where Match is a SQL "LIKE" and Term is a SQL "=". In large documents Term will most likely be the fastest alternative.

Proposed solution:

var search = client.Search<Person>(s => s
        .Index("people_*")
        .From(0)
        .Size(10)
        .Term(q => q
        .Field(p => p.FavoriteColor)
        .Value("Red")));

Upvotes: 2

Related Questions