0
votes

I'm looking for a way to create a text-based query that could match value from a boolean field.

In words of example – my query could be "Red carpet artificial" or "Artificial red carpet" and I have documents with boolean field mapped as artificial: true/false. With that phrases I need to match documents that have artificial: true.


This is the data stored in index:

[
  {
    "name": "Fast car",
    "artificial": true
  },
  {
    "name": "Red carpet",
    "artificial": true
  },
  {
    "name": "Green carpet of grass",
    "artificial": false
  },
  {
    "name": "Lovely bunny",
    "artificial": false
  },
  {
    "name": "Big house",
    "artificial": true
  },
  {
    "name": "Green plant",
    "artificial": false
  }
]

Now I have user-input search phrases like:

  • "Artificial carpet"
  • "Carpet (artificial)"
  • "Carpet – Artificial"

I need to construct query that when entering above phrases will always return:

  {
    "name": "Red carpet",
    "artificial": true
  }

But when user enters:

  • "Carpet"

It will actually return:

  {
    "name": "Green carpet of grass",
    "artificial": false
  }

(Or both "carpet"-consisting documents it that would be easier to achieve.)

The thing is I need search phrase tokenization here, because "artificial" can be named in different kind of ways.

And "artificial" is my keyword that does not suppose to change.


Is there a mechanism or some kind of workflow in Elasticsearch to achieve this? Maybe re-mapping artificial: (bool) true/false to artificial: (keyword) artificial/null or something? How would query look like then?

1

1 Answers

0
votes

I ended up using new 7.11 Elasticsearch feature called Runtime mapping fields.

Created new field based on boolean field that converts true/false to keyword representation of this field versus empty string. Then – used "terms" query.

{
  "runtime_mappings": {
    "myfield_keyword": {
      "type": "keyword",
      "script": {
        "source": "emit(doc['myfield'].value ? 'value' : '')"
      }
    }
  },
  "query": {
    "bool": {
      "should": [
        {
          "terms": {
            "boost": 2,
            "myfield_keyword": [
              "search",
              "phrase",
              "tokenized",
              "manually"
            ]
          }
        },
// ...