DarrenY
DarrenY

Reputation: 21

Elasticsearch Nest - Searching on Dynamic Data

I have an index being automapped from a fairly simple model.

The only complexity is a list of dynamic values where the users can create their own data. Each value has a Title (what the data is) and a Value. For example, 2 items in the array might be:

Item 1

Item 2

There could be many of these and we don't know what they'll be. They can be added by users in the CMS.

My classes look something like this:

public class SearchRequest
{
    public int DocumentId { get; set; }
    public string DocumentName { get; set; }

    public List<DynamicTextValue> DynamicTextValues { get; set; }
}

public class DynamicTextValue
{
    public string Title { get; set; }
    public string Value { get; set; }
}

The generic mapping looks like this:

"documentId": {
    "type": "integer"
},
"documentName": {
    "type": "text"
},
"dynamicTextValues": {
    "properties": {
        "value": {
            "type": "text"
        },
        "title": {
            "type": "text",
            "fields": {
                "keyword": {
                    "type": "keyword",
                    "ignore_above": 256
                }
            }
        }
    }
}

I also have dynamicNumericValues and dynamicDateValues with a similar concept.

The problem is when I want to search on one of the dynamic types. Let's say I search for surname "Thomas". I add 2 "must" searches:

Or

This won't work because the two fields are independent of each other. It will actually return records where any Value is Thomas (e.g. Thomas is also a First Name) as long as it contains a title with Surname somewhere in the same record. I need it to return only where Value is Thomas on the same list item that the Title is Surname.

Is there any way this can be done? Or is there a better way to structure my data to achieve these results? I considered (as a hack) concatenating the Title and Value and searching for "Surname Thomas" but this won't solve the problem for numeric and date fields.

Upvotes: 1

Views: 302

Answers (1)

Russ Cam
Russ Cam

Reputation: 125498

DynamicTextValue needs to be mapped as a nested data type for this to work. nested data types are internally mapped as separate documents, maintaining the relationship between the properties, title and value in this case.

Upvotes: 1

Related Questions