javaazure-cosmosdbazure-cognitive-searchazure-java-tools

How to search different texts in multiple fields in Azure AI/Cognitive Search (Azure.search.documents)?


So, I want to have fields A, B, and C be searchable so that if I look search up some string "potato", it will look for that word in fields A, B, and C.

To do that, I created an index in Azure Search where A, B, and C are retrievable and searchable. This part works as expected.

What if I wanted to add in field D as well, but I want to it to be searched/filtered separately from ABC? Like if I am looking for (don't mind the syntax) ABC = "potato" AND D = "brand 1" , do I have to create a whole new index for just searching D?

What I have right now is one index with A, B, and C marked as searchable, and D is marked as filterable.

In the java code, I have a searchClient that uses that index.

SearchOptions searchOptions = new SearchOptions()
    .setSearchFields(
        "A",
        "B",
        "C"
    );
SearchPagedIterable searchResults = searchClient.search("potato", searchOptions, Context.NONE);

I'm not sure how to add field D into the above code because I don't want to search field D for "potato" nor fields ABC for "brand 1".

If I need to create an index per separate searchable field, that is doable. My only problem is that I have a lot of fields. If I needed to have an index to search them all, that is a lot of indexes and java code.

Ideally, there is a way through SearchOptions or SearchClient that I am able to separate searches so I can do something like "potato" AND D = "brand 1"

I also see this question which is very similar but with no answers: Azure Cognitive Search multiple fields with different text


Solution

  • Can you try something like the following (untested code):

    SearchOptions searchOptions = new SearchOptions()
        .setSearchFields(
            "A",
            "B",
            "C"
        )
        .setFilter("D eq 'brand 1'")
    SearchPagedIterable searchResults = searchClient.search("potato", searchOptions, Context.NONE);
    

    What this code should do is do a search for potato in fields A, B, C and do a OData filter query on field D.