How to search in elastic search with separated by space and without space

Viewed 489

My Query is below

  • I am searching for L1 L2 in the elastic search cluster with some aggregation function
  • I am converting L1 L2 to L1 OR L2

Requirement

  • I need to search on L1 L2 first (high weigtage)
  • Then I need to search on L1 and L2 separately.

My Template is below need to update in 'query': '**L1* OR *L2**

template =  {
  'from': 0,
  'size': 10,
  'aggs': {
    'Tester': {
      'terms': {
        'field': 'Tester.name.keyword',
        'order': {
          '_key': 'desc'
        }
      }
    },
    'Developer': {
      'terms': {
        'field': 'Developer.name.keyword',
        'order': {
          '_key': 'desc'
        }
      }
    },
    'Analyst': {
      'terms': {
        'field': 'Analyst.name.keyword',
        'order': {
          '_key': 'desc'
        }
      }
    }
  },
  'query': {
    'bool': {
      'must': {
        'query_string': {
          'query': '**L1* OR *L2**'
        }
      },
      'filter': {
        'term': {
          'parentName.keyword': 'Software Department'
        }
      }
    }
  }
}

Is there way to achieve without change in settings

1 Answers

As suggested by @David in the comment, you can use the shingles token filter to achieve your use-case.

Adding a working example, which clearly shows the higher score for docs conatining L1 L2 while L1 and L2 docs also coming in search results.

Index mapping

{
    "settings": {
        "analysis": {
            "analyzer": {
                "my_analyzer": {
                    "type": "custom",
                    "tokenizer": "whitespace",
                    "filter": [
                        "shingle"
                    ]
                }
            }
        }
    },
    "mappings": {
        "properties": {
            "name": {
                "type": "text",
                "analyzer": "my_analyzer"
            }
        }
    }
}

Index sample docs

{
    "name" : "L1 L2"
}

{
    "name" : "L1"
}
{
    "name" : "L2"
}

Search query

{
    "query": {
        "match": {
            "name": "L1 L2"
        }
    }
}

And search response

 "hits": [
            {
                "_index": "shingleside",
                "_type": "_doc",
                "_id": "1",
                "_score": 1.0462961,
                "_source": {
                    "name": "L1 L2"
                }
            },
            {
                "_index": "shingleside",
                "_type": "_doc",
                "_id": "2",
                "_score": 0.5619608,
                "_source": {
                    "name": "L1"
                }
            },
            {
                "_index": "shingleside",
                "_type": "_doc",
                "_id": "3",
                "_score": 0.5619608,
                "_source": {
                    "name": "L2"
                }
            }
        ]
Related