I am unable to create index in Azure AI search using C#

AJITH KRISHNA MANKENA 0 Reputation points
2024-12-26T16:18:20.36+00:00

I have followed below git repo to create index in Azure AI Search (Line 231 - 307) https://github.com/Azure/azure-search-vector-samples/blob/main/demo-dotnet/DotNetVectorDemo/Program.cs
I am not using SemanticSearch so removed code from Line 266 - 283

Below is the code

public static async Task Main(string[] args)

{

SetUpIndex();

}

public static async Task SetUpIndex()

{

const string vectorSearchHnswProfile = "my-vector-profile";

const string vectorSearchHnswConfig = "myHnsw";

const string vectorSearchVectorizer = "myOpenAIVectorizer";

const string semanticSearchConfig = "my-semantic-config";

const string indexName = "my-demo-index-dummyindex";

const string AzureOpenAIEmbeddingDimensions = "1024";

try

{

    Console.WriteLine("Initializing Azure Search Service");

    SearchIndexClient indexclient = new SearchIndexClient(new Uri(searchServiceEndpoint), new AzureKeyCredential(searchApiKey));

//passing searchServiceEndpoint and key in searchApiKey

    Console.WriteLine("Connected to Azure AI Search");

    SearchIndex searchIndex = new(indexName)

    {

        VectorSearch = new()

        {

            Profiles =

        {

            new VectorSearchProfile(vectorSearchHnswProfile, vectorSearchHnswConfig)

            {

                VectorizerName = vectorSearchVectorizer

            }

        },

            Algorithms =

            {

                new HnswAlgorithmConfiguration(vectorSearchHnswConfig)

            },

            Vectorizers =

            {

            new AzureOpenAIVectorizer(vectorSearchVectorizer)

            {

                Parameters = new AzureOpenAIVectorizerParameters

                {

                    ResourceUri = new Uri(openaiApiBase), // Azure Open AI endpoint

                    ApiKey = openaiApiKey, //Azure open AI Key 

                    ModelName = deploymentName, // using text-embedding-3-large model for embedding

                    DeploymentName = deploymentName

                }

            }

            },

        },

        Fields =

    {

        new SimpleField("id", SearchFieldDataType.String) { IsKey = true, IsFilterable = true, IsSortable = true, IsFacetable = true },

        new SearchableField("title") { IsFilterable = true, IsSortable = true },

        new SearchableField("content") { IsFilterable = true, IsSortable = true },

        new SearchField("contentVector", SearchFieldDataType.Collection(SearchFieldDataType.Single))

        {

            IsSearchable = true,

            VectorSearchDimensions = int.Parse(AzureOpenAIEmbeddingDimensions),

            VectorSearchProfileName = vectorSearchHnswProfile

        },

        new SearchableField("category") { IsFilterable = true, IsSortable = true, IsFacetable = true }

    }

    };

    Console.WriteLine(searchIndex.Name.ToString());

    Console.WriteLine("Creating Index");

    //await indexclient.CreateIndexAsync(searchIndex); //first tried with this, its not working

    await indexclient.CreateOrUpdateIndexAsync(searchIndex);

    Console.WriteLine($"Index created successfully {indexName}");

}

catch (RequestFailedException ex)

{

    Console.WriteLine($"Error creating index: {ex.Message}");

}

catch (Exception ex)

{

    Console.WriteLine($"Error creating index: {ex.Message}");

}

}

The code is not even throwing any errors or exceptions. It's printing Console.WriteLine("Creating Index"); on console but when entering await indexclient.CreateOrUpdateIndexAsync(searchIndex); program is simply terminating. No exception is being thrown or printed on the console. Any support on this issue is very helpful.

Azure AI Search
Azure AI Search
An Azure search service with built-in artificial intelligence capabilities that enrich information to help identify and explore relevant content at scale.
1,118 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,156 questions
Azure AI services
Azure AI services
A group of Azure services, SDKs, and APIs designed to make apps more intelligent, engaging, and discoverable.
3,002 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Sina Salam 14,626 Reputation points
    2024-12-27T17:17:42.7233333+00:00

    Hello AJITH KRISHNA MANKENA,

    Welcome to the Microsoft Q&A and thank you for posting your questions here.

    I understand that you are having issue of unexpected termination without exceptions.

    My first advice is to verifying API key, endpoint configurations and simplifying the index creation code.

    To address the root cause of silent termination comprehensively, follow the following steps:

    1. Attach a debugger and step through the code to observe where it terminates. Pay close attention to the CreateOrUpdateIndexAsync method.
              AzureEventSourceListener listener = new AzureEventSourceListener((eventData, text) => 
              {
                  Console.WriteLine($"{eventData.Level}: {text}");
              }, System.Diagnostics.Tracing.EventLevel.LogAlways);
      
      This enables detailed logs from Azure SDK to identify potential internal errors.
    2. Then, add a global exception handler to catch unhandled exceptions:
              AppDomain.CurrentDomain.UnhandledException += (sender, args) =>
              {
                  Console.WriteLine($"Unhandled exception: {args.ExceptionObject}");
              };
      
    3. Confirm the validity of searchServiceEndpoint and searchApiKey by running a simple API call like listing indexes:
              var response = await indexClient.GetIndexAsync(indexName);
              Console.WriteLine(response.Value.Name);
      
      Ensure the API key has Index Administrator permissions in Azure AI Search.
    4. Start with minimal schema:
            SearchIndex searchIndex = new(indexName)
            {
                Fields = new[]
                {
                    new SimpleField("id", SearchFieldDataType.String) { IsKey = true }
                }
            };
            await indexClient.CreateOrUpdateIndexAsync(searchIndex);
      
    5. Run the program locally and in a different environment (e.g., another machine or Azure Function) to rule out environment-specific issues like insufficient memory or runtime incompatibility.
    6. Use a tool like ProcDump (for Windows) or gcore (for Linux) to capture crash dumps if the application exits unexpectedly using bash or CMD: procdump -e -ma YourApp.exe
    7. Check Azure AI Search’s diagnostic logs for any failed operations.

    The below is a revised code snippet for you:

    public static async Task SetUpIndex()
    {
        const string indexName = "my-demo-index-dummyindex";
        try
        {
            Console.WriteLine("Initializing Azure Search Service");
            SearchIndexClient indexClient = new SearchIndexClient(new Uri(searchServiceEndpoint), new AzureKeyCredential(searchApiKey));
            Console.WriteLine("Connected to Azure AI Search");
            // Minimal schema for testing
            SearchIndex searchIndex = new(indexName)
            {
                Fields = new[]
                {
                    new SimpleField("id", SearchFieldDataType.String) { IsKey = true }
                }
            };
            Console.WriteLine("Creating Index");
            await indexClient.CreateOrUpdateIndexAsync(searchIndex);
            Console.WriteLine($"Index created successfully: {indexName}");
        }
        catch (RequestFailedException ex)
        {
            Console.WriteLine($"Error creating index: {ex.Message}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Unexpected error: {ex.Message}");
        }
    }
    

    I hope this is helpful! Do not hesitate to let me know if you have any other questions.


    Please don't forget to close up the thread here by upvoting and accept it as an answer if it is helpful.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.